【问题标题】:How to add object to document before returning it?如何在返回之前将对象添加到文档中?
【发布时间】:2020-01-13 17:31:51
【问题描述】:

我想解决以下问题: 通过 angularfire 从 Firestore 获取集合后,我想遍历这些集合中的每个文档,而不是执行单独的 Firestore 请求以获取相应的文档,在返回集合之前,我希望将这些值插入到第一个文档中。

例如,有一个名为ball 的对象,其属性

interface Ball: {
  uid: string; 
  color: string;
}

还有一个带有属性的对象player

interface Player: {
  uid: string;
  correspondingBall: ball;
}

在 Firestore 集合中,我保存了一个来自 Player 类型的文档,其中包含来自相应球的相应 id(我希望你知道我的意思)。 现在,我访问收藏播放器

getRecentPlayers(): Observable<Player[]> {
    const players: AngularFirestoreCollection<any> = this.angularFirestore.collection<Player>('players');
    return players ? players.snapshotChanges().pipe(
      map(players => {
        return players.map(player => {
          const data = player.payload.doc.data() as Player;
          const correspondingBall: AngularFirestoreDocument<Ball> = this.angularFirestore.doc('balls/' + data.correspondingBall);
          correspondingBall ? correspondingBall.snapshotChanges().pipe(
            map(ball => {
              const data = ball.payload.data() as Ball;
              return data;
            })
          ) : null;
          return {...data, correspondingBall}
        })
      })
    ) : null;
  }

那样,我不会工作。有人能帮我吗? 非常感谢!!

【问题讨论】:

    标签: angular typescript firebase google-cloud-firestore angularfire2


    【解决方案1】:

    一般的方法是:进行咨询(返回一个值数组),创建一个 switchMap,创建一个可观察的数组,创建一个 forkjoin,使用索引映射以添加新属性。我使用 simples 获取代码

    getPlayers().pipe(
      switchMap(players=>{
        //in players we has an array of player
        //create an array of observables with the array
        const obs=players.map(player=>getBall(player.ballId)
        //a switchMap must return an observable, so return a forkJoin
        return forkjoin(obs).pipe(
           //but we transform the result that is an array
           //with the values of getBall(1),getBall(2)..
           map((ball,index)=>{
              //concat the properties of players[index] with the ball
              return {...players[index],..ball}
           })
        )
      }
    )).subscribe(res=>console.log(res))
    

    【讨论】:

      猜你喜欢
      • 2020-03-31
      • 1970-01-01
      • 2014-05-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多