与集合数组结果中的对象联接

时间:2018-10-14 02:52:43

标签: angular firebase google-cloud-firestore angularfire2

我有2个收藏集:

用户:uid,displayName。

活动:用户可以创建的文档。它还包含userUid及其对Users集合的引用

我得到了这样的活动:

this.activities = this.afs.collection<Activity>('activities')
 .snapshotChanges()
 .pipe(
   map((actions) => {
    return actions.map((a) => {
      const data = a.payload.doc.data();
      data.uid = a.payload.doc.id;
      return data;
    })
  }));

所以,我的问题是加入并获取用户数据的最佳方法是什么?

我这样尝试过:

actReference.snapshotChanges().pipe(
  map((actions) => {
    return actions.map((a) => {
      const actData = a.payload.doc.data();
      actData.uid = a.payload.doc.id;

      return this.userService.getUserDocById(actData.userUid).snapshotChanges()
        .pipe(
          map((userActions) => {
            const userData = userActions.payload.data();
            return { user: { uid: userData.uid, displayName: userData.displayName }, ...actData };
          }))
    })
  }));

但是它给了我一个

 Observable<Observable<Activity>[]>>

2 个答案:

答案 0 :(得分:0)

您需要应用rxjs管道运算符链接。

actReference.snapshotChanges().pipe(
  map((actions) => {
    actions.map((a) => ({
      let actData = a.payload.doc.data();
      actData.uid = a.payload.doc.id;
      actData.displayName = a.payload.doc.name;
      return actData;
    });
  }),
  map((userData) => {
      return this.userService.getUserDocById(actData.userUid).snapshotChanges()
        .pipe(
          map((userActions) => {
            const userData = userActions.payload.data();
            return { user: { uid: userData.uid, displayName: userData.displayName }, ...actData };
          }))
    })
  }));

答案 1 :(得分:0)

@ suresh-kumar-ariya的回答不是我的最终结果,但对我有很大帮助,我最终得到了以下代码:

 return actReference.snapshotChanges().pipe(
  map((actions) => {
    return actions.map((a) => {
      const actData = a.payload.doc.data();
      actData.uid = a.payload.doc.id;

      return this.userService.getUserDocById(actData.userUid).snapshotChanges()
        .pipe(
          map((userActions) => {
            const userData = userActions.payload.data();
            return { user: { uid: userData.uid, displayName: userData.displayName }, ...actData } as Activity;
          }))
    })
  }),
  mergeMap(obs => combineLatest(obs))
);