【问题标题】:Extract value from observable in typescript从打字稿中的可观察值中提取值
【发布时间】:2020-12-14 23:10:53
【问题描述】:

我的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

【问题讨论】:

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


    【解决方案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后,将返回的observable切换到提供id的firestore.collection。

    【讨论】:

      猜你喜欢
      • 2020-11-11
      • 2022-07-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多