从打字稿中的可观察值中提取值

时间:2020-08-26 07:38:08

标签: javascript angular asynchronous google-cloud-firestore rxjs

我的user$: Observable<User>;中有AuthService。我也有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

1 个答案:

答案 0 :(得分:1)

这部分是异步的:

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后,它将使用提供的ID将返回的observable切换到firestore.collection。

相关问题