我有一个设置,我可以在其中查询 firebase 以获取用户最喜欢的帖子列表。
基本上,一开始我查询用户点赞,然后为每个点赞获取相应的帖子 - 所有这些都在一个可观察的序列中。
当用户不喜欢唯一留下的帖子时,就会出现问题。在这种情况下(当 likes 数组变为空时)observable 不会触发任何东西, View 也不会更新(总是至少有一个帖子存在)。
一方面,这种行为看起来合乎逻辑且可以理解,但另一方面,即使 switchMap 的输入为空,我也不确定如何让最终的 Observable 发出。也许应该更换运营商。
getUserFavourites(userId = ""):Observable<Post[]>
{
if (!this.userFavourites$) {
this.userFavourites$ = this.af.database.list('/ranks_by_user/' + userId, {
query: {
limitToFirst: 50
}
}) //Emits value here (even empty array)
.switchMap((likes: any[]) => Observable.combineLatest(
likes.map(like => this.af.database.object("/posts/" + like.$key).first())
)) //Does not emit new value here if likes array was empty
.map(p => {
return p.map(cit => Post.unpack(p));
}).publishReplay(1).refCount()
}
return this.userFavourites$;
}
最佳答案
通过在 switchMap 中添加条件解决了问题:
原创 - https://github.com/ReactiveX/rxjs/issues/1910
getUserFavourites(userId = ""):Observable<Post[]>
{
if (!this.userFavourites$) {
this.userFavourites$ = this.af.database.list('/ranks_by_user/' + userId, {
query: {
limitToFirst: 50
}
}) //Emits value here (even empty array)
.switchMap((likes: any[]) => {
return likes.length === 0 ?
Observable.of(likes) :
Observable.combineLatest(
likes.map(like => this.af.database.object("/citations/" + like.$key))
)
}) //Emits either combined observables array or empty array
.map(p => {
return p.map(cit => Post.unpack(p));
}).publishReplay(1).refCount()
}
return this.userFavourites$;
}
关于angular - RxJS - 如果输入可观察对象为空数组,则 switchMap 不会发出值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41723541/