簡體   English   中英

Angular 等待組件間服務,行為主體

[英]Angular await service between components, Behavior Subject

當我刷新 window 時,我的 Angular web 商店中有一個問題,我創建了一個服務,該服務從服務器獲取用戶數據,然后注入到“產品”部分,以提出一個請求:

 import { Injectable } from '@angular/core'; import { BehaviorSubject } from 'rxjs/BehaviorSubject'; @Injectable({ providedIn: 'root' }) export class DataService { private userId = new BehaviorSubject<any>(''); currentUserId = this.userId.asObservable(); constructor() { } sendUserId(message: string){ this.userId.next(message) } }

這工作正常,但問題是當我在產品部分刷新 window 時,在控制台中我可以看到該服務獲取用戶數據但是當我 getProducts() 它拋出錯誤時,似乎 getProducts() 在服務有響應,我需要用戶 ID 來提出產品請求。 我的問題:有沒有辦法等待 BehaviorSubject 的響應,然后發出 getProducts() 請求? 這是產品部分的代碼:

 ngOnInit(): void { this._dataService.currentUserId.subscribe(userId => this.userId = userId); if(this.userId.length === 0){ this.userService.getUserProfile().subscribe( res => { this.userDetails = res['user']; this.userId = this.userDetails._id; this.getProducts(); }, err => { console.log(err); } ); } else { this.getProducts(); } }

如您所見,我做了一個條件來檢查 userId 是否存在,如果不存在,我必須提出新的用戶請求,這修復了錯誤,但我認為有更好的方法來解決這個問題。 提前致謝。

如何將所有邏輯放在observernext function 中,如下所示:

this._dataService.currentUserId.subscribe(userId => {
  if (userId.length === 0)
  {
    this.userService.getUserProfile().subscribe(
      res => {
        this.userDetails = res['user'];
        this.userId = this.userDetails._id;
        this.getProducts();
      },
      err => {
        console.log(err);
      }
    );
  } else
  {
    this.getProducts();
  }
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM