簡體   English   中英

Angular 在啟動其他 Observable 之前等待一個 Observable 完成

[英]Angular Wait an Observable to finish before starting other Observable

我有兩個 Observables :

constructor(
    private afAuth:AngularFireAuth,
    private db:AngularFireDatabase
    ) {
      
    this.afAuth.authState.subscribe(x=> 
      {
        this.userId=x?.uid;
        console.log(this.userId);
      });
      
      console.log(this.userId);
      this.db.list('users/'+this.userId+'/movies-favourited').valueChanges().subscribe(data=>{
        this.favouriteList=data;
      });
   }

在第二個 Observable 中獲取列表之前,如何確保在第一個 Observable 中獲取 userId。

正確的做法是使用switchMap ,如下所示:

this.afAuth.authState.pipe(
    switchMap(user => {
        if(user) {
            this.userId = user.uid;
            this.db.list('users/'+this.userId+'/movies-favourited')
                .valueChanges().subscribe(data => {
                    this.favouriteList = data;
                });
        }
    })
);

您可以在此處閱讀有關switchMap更多信息。

您可以用 promise 替換第一個 observable

或者

您可以像這樣將第二個 observable 放在第一個 observable 中:

this.afAuth.authState.subscribe(x=> 
  {
    this.userId=x?.uid;
    console.log(this.userId);
  this.db.list('users/'+this.userId+'/movies-favourited').valueChanges().subscribe(data=>{
    this.favouriteList=data;
    });
  });

一旦第一個 observable 通過訂閱成功檢索數據,它將訂閱第二個 observable,這將解決您的問題。

constructor(
    private afAuth: AngularFireAuth,
    private db: AngularFireDatabase
) {
    this.afAuth.authState.subscribe(x => {
        this.userId = x?.uid;
        console.log(this.userId);
        this.db.list('users/' + this.userId + '/movies-favourited').valueChanges().subscribe(data => {
            this.favouriteList = data;
        });
        console.log(this.userId);
    });
}

這必須是您任務的解決方案。

this.afAuth.authState
                .subscribe(
                    (x: any) => {
                        this.userId = x?.uid;
                        if (x.uid) {
                            this.db.list('users/' + this.userId + '/movies-favourited').valueChanges()
                                .subscribe(
                                    (data: any) => {
                                        this.favouriteList = data;
                                    },
                                    (error) => {
                                        console.log(error);
                                    });
                        }
    
                    },
                    (error) => {
                        console.log(error);
                    }
                );

更多優化代碼的建議:

  1. 考慮將您的代碼放在 ngOnInit() 生命周期中而不是構造函數中。
  2. 定義變量“x”和“data”的數據類型。
  3. 不要忘記取消訂閱。
  4. 以某種方式處理你的錯誤。

暫無
暫無

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

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