我对Observables和rxjs的整个概念是陌生的,所以这可能很明显。但是,由于我急于学习,请提供帮助
当用户单击以在博客文章下显示评论时,我很高兴
showComments(){
this.firestoreservice.getComments(this.job.id).subscribe( data =>{
this.comments = data //type [] of comment objects with (message,posterID,timeposted...)
})
this._showcomments = true;
}
此函数调用一个服务函数,该函数将可观察到的内容返回到该作业的我的注释列表。 在可观察的订阅中,初始化一个变量来保存我的所有评论。 但是,在执行此操作之前,是否可以用匹配的用户名替换每个评论的posterID属性?参见下面的预期结果:
showComments(){
this.firestoreservice.getComments(this.job.id).subscribe( data =>{
//for each comment held in data, replace comment.posterID with getUserName(posterID)
//getUserName(posterID) will also return an observable which emmits one string
//then append comment to comments list (or add back in to data then destructively assign
//comments=data )
this.comments = data //type [] of comment objects with (message,posterID,timeposted...)
})
this._showcomments = true;
}
答案 0 :(得分:1)
它看起来有点像这样。...
this.firestoreservice.getComments(this.job.id).pipe(
switchMap(comments => { // switchMap to subscribe to inner
const getUsers$ = comments.map(comment => // array map comments into userName fetch
this.firestoreservice.getUserName(comment.posterID).pipe(
// once you have the username, rx map back into the comment with the username assigned
map(userName => ({...comment, posterID: userName})),
first() // use to complete after one emission to make forkJoin work
)
)
return forkJoin(...getUsers$); // forkJoin them all together for parallel execution
});
).subscribe(data => {
this.comments = data // now just set the data
})