从typescript中的observable中提取值



我的AuthService中有user$: Observable<User>;。我也有OrderService。我想根据User.id(获取所有用户订单(提出请求。

这是我的功能:

getUserOrders() {
let id;
this.authService.user$.pipe(take(1)).subscribe(data => id = data.uid);
return this.firestore.collection('orders', ref => ref.where("purchaserId","==", id)).snapshotChanges().pipe(
map(changes => {
return changes.map(a => {
let data = a.payload.doc.data() as Order;
data.id = a.payload.doc.id;
return data;
});
})
);
}

问题是这条线:

let id;
this.authService.user$.pipe(take(1)).subscribe(data => id = data.uid);

因为在调用return语句时id保持未定义状态。所以我得到错误Function Query.where() requires a valid third argument, but it was undefined.

我知道在html中使用异步管道很方便。但我认为在打字稿中使用observable会让它变得更难。我认为更好的解决方案是将user$: Observable<User>更改为user: User

这部分是异步的:

this.authService.user$.pipe(take(1)).subscribe(data => id = data.uid);

因此,当调用firestore.collection时,id还没有用data.uid初始化。

您可以将getUserOrders更改为:

return this.authService.user$.pipe(
take(1),
switchMap(({uid}) => {
return return this.firestore.collection('orders', ref => 
ref.where("purchaserId","==", uid)).snapshotChanges().pipe(
map(changes => {
return changes.map(a => {
let data = a.payload.doc.data() as Order;
data.id = a.payload.doc.id;
return data;
});
})
);
})
)

在获得id后,它将返回的observable切换到firestore.collection并提供id。

最新更新