我想解决以下问题: 在通过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;
}
那样,我不会工作。有人能帮我吗? 非常感谢你!
答案 0 :(得分:2)
通常的方式是:进行咨询(返回值数组),进行switchMap,创建可观察对象数组,进行forkjoin,使用索引进行映射以添加新属性。我用简单的gets去编码
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))