![](/img/trans.png)
[英]Angular : Wait for an Observable to finish before returning the value
[英]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);
}
);
更多優化代碼的建議:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.