尝试使用angularfire以角度加入一对多Firebase文档

问题描述 投票:1回答:1

我知道之前已经有人问过这个问题,但是我无法从提供的典型答案中弄清楚我的情况。在我的应用程序中,我有称为目标的firebase集合和具有一对多关系的任务集合。每个目标都有一个任务数组(填充有任务的ID),每个任务都有一个ObjectiveId。我想加入这些对象,所以当我进行snapshotChanges()调用以获取所有目标时,我想返回一个嵌套了任务对象的目标数组。

我有这段代码,我知道它不起作用,因为我无法以可观察的方式返回某些内容,但我想知道在这种情况下如何使用RxJS运算符?

loadObjectives() {
 return this.objectivesCollection.snapshotChanges().pipe(
  map(actions => {
    return actions.map(_ => {
      const id = _.payload.doc.id;
      const data = _.payload.doc.data();
      const tasks = this.afs
        .collection<Task>("tasks", ref =>
          ref.where("objectiveId", "==", id)
        )
        .valueChanges().subscribe( tasks => {
          return new Objective(id, data.title, tasks);
        });
    });
  }),
  tap(objectives => {
    this._objectives.next(objectives);
  })
);}
typescript firebase google-cloud-firestore rxjs angularfire
1个回答
0
投票

这可以通过一些聪明的RxJS代码来完成,但是通过在组件之间传递props来连接数据通常更容易。例如,首先阅读您的目标,然后将ID传递给孩子以运行另一个任务查询。

<objectives-list *ngFor="let obj of objectivesCollection | async">

   <tasks-list [objective]="obj">

但是要回答您的问题,下面的代码将从目标开始,然后将每个结果映射到任务查询。最终结果将是一个数组数组(任务集合)。

this.objectivesCollection.valueChanges({idField: 'id'}).pipe(
  switchMap(objectives => {

     // map each objective to a task query

      const joins = objectives.map(obj => this.afs
          .collection<Task>("tasks", ref => ref.where("objectiveId", "==", obj.id))
          .valueChanges()
         )

      // execute all queries concurrently with combineLatest. 
      return combineLatest(joins)

   })
)
© www.soinside.com 2019 - 2024. All rights reserved.