[英]Extract value from observable in typescript
I have user$: Observable<User>;
我有
user$: Observable<User>;
in my AuthService
.在我的
AuthService
。 I hace OrderService
too.我也有
OrderService
。 I want to make request based on User.id (Getting all users orders).我想根据 User.id 发出请求(获取所有用户的订单)。
This my function:这是我的功能:
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;
});
})
);
}
The problem is this line:问题是这一行:
let id;
this.authService.user$.pipe(take(1)).subscribe(data => id = data.uid);
Because id stays undefined when return statement is called.因为调用 return 语句时 id 保持未定义状态。 So i get error
Function Query.where() requires a valid third argument, but it was undefined.
所以我得到错误
Function Query.where() requires a valid third argument, but it was undefined.
I know working with async pipe is convenient in html.我知道在 html 中使用异步管道很方便。 But i think using observable in typescript makes it harder.
但我认为在打字稿中使用 observable 会让它变得更难。 I think better solution would be to change
user$: Observable<User>
to user: User
.我认为更好的解决方案是将
user$: Observable<User>
更改为user: User
。
This part is asynchronous :这部分是异步的:
this.authService.user$.pipe(take(1)).subscribe(data => id = data.uid);
So id
isn't initialised yet with data.uid
when firestore.collection is called.所以当firestore.collection被调用时,
id
还没data.uid
初始化。
You can change getUserOrders
to :您可以将
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;
});
})
);
})
)
After getting the id, it switchs the returned observable to the firestore.collection with the provided id.获取 id 后,它将返回的 observable 切换到具有提供的 id 的 firestore.collection。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.