【问题标题】:Angularfire2 attach more data to user collectionAngularfire2 将更多数据附加到用户集合
【发布时间】:2020-01-17 15:14:15
【问题描述】:

我正在创建一个应用程序,用户可以在其中创建组。群组集合存储在每个用户内部,如果群组广告成员的所有者对应的用户 id 和角色仅保存在群组集合中。因此,当所有者访问组成员时,我希望显示在另一个集合中的用户的完整信息。

这是我的 firestore 数据库中的两个集合

this.afs.collection(`users/${ownerId}/groups/${gid}/users`)
this.afs.doc(`users/${ownerId}`) //full user data

这是我在我的服务中访问用户的方式

getGroupUsers(gid, ownerId) {
return this.afs.collection(`users/${ownerId}/groups/${gid}/users`).snapshotChanges().pipe(
    map(actions => actions.map(a => {
      const data = a.payload.doc.data();
      const userId = a.payload.doc.id;
      return { userId, ...data };
    })
    )
  );
}

这里userId 是每个用户的唯一ID,我希望向...data 对象添加更多数据。我尝试了很多方法都失败了,这就是我试图实现的目标

getGroupUsers(gid, ownerId) {
return this.afs.collection(`users/${ownerId}/groups/${gid}/users`).snapshotChanges().pipe(
  map(actions => actions.map(a => {
    const data = a.payload.doc.data();
    const userId = a.payload.doc.id;
    //return { userId, ...data };
    return this.afs.doc(`users/${userId}`).valueChanges().pipe(
      map(userData => {
        return {userId, ...data, ...userData}
      })
    )
  })
  )
);
}

我使用angular 8.1.2Rxjs 6.4.0。 请帮忙。

【问题讨论】:

    标签: angular firebase google-cloud-firestore angularfire2


    【解决方案1】:

    未经测试,但您可以使用mergeMapswitchMapcombineLatest 的组合。 switchMap 切换到内部 observable,combineLatest 执行嵌套请求。

    getGroupUsers(gid, ownerId) {
      return this.afs.collection(`users/${ownerId}/groups/${gid}/users`).snapshotChanges().pipe(
        switchMap(actions => combineLatest(
          actions.map(a => {
            const data = a.payload.doc.data();
            const userId = a.payload.doc.id;
            return this.afs.doc(`users/${userId}`).valueChanges().pipe(
              map(userData => {
                return { userId, ...data, ...userData }
              })
            )
          })
        ))
      );
    }
    

    【讨论】:

    • 我试过你的代码,但它抛出了这个错误Uncaught TypeError: You provided 'function (source) { return source.lift.call(from_1.from([source].concat(observables)), new combineLatest_1.CombineLatestOperator(project)); }' where a stream was expected. You can provide an Observable, Promise, Array, or Iterable.
    • 嗯...刚刚在一个 firebase 项目上测试了这段代码,它工作得很好。
    • 好的,感谢您的确认。我发现问题在于combineLatest 导入。我将import { combineLatest } from 'rxjs/operators'; 更改为import { combineLatest } from 'rxjs';。现在它工作正常。再次感谢您的帮助。
    • 哦,是的,为了清楚起见,我本可以添加导入,但很高兴您能想到 :) 是的,非常欢迎您!
    猜你喜欢
    • 2020-01-18
    • 1970-01-01
    • 1970-01-01
    • 2013-10-26
    • 1970-01-01
    • 2021-03-03
    • 1970-01-01
    • 2017-07-18
    • 1970-01-01
    相关资源
    最近更新 更多