我是 Rxjs 的新手,正在尝试编写一些代码
combineLatest( [poll$, user$ ]).subscribe( ([poll, user]) => {
this.poll = poll;
if( user.participated_in_polls.includes( poll._id )) {
this.already_participated = true;
return;
}
this.questionsService.get( poll._id ).subscribe( response => {
this.questions = this.questionsQuery.getActive();
});
})
我读过应该避免嵌套订阅。但是我不知道我应该如何编写此代码以避免嵌套 subscribe
有人可以帮忙吗?
谢谢
答案 0 :(得分:1)
您确实想开始使用管道运算符和更高阶的可观察映射运算符,例如 mergeMap、switchMap、concatMap 等。然后,您可以对值流而不是嵌套订阅进行操作。
请注意我仅传达的概念:
combineLatest([poll$, user$])
.pipe(
tap((x) => this.poll = poll),
filter((thing) => user.participated_in_polls.includes(poll._id)),
mergeMap((otherThing) => {
return this.questionsService.get(poll._id);
})
)
.subscribe((streamEnd) => {
this.questions = this.questionsQuery.getActive();
});