如何将 rxjs 用于多个内部嵌套订阅
How to use rxjs for multiple inner nested subscribes
在下面的代码中,我在订阅中使用了订阅。此代码有效,但代码结构非常糟糕。我想使用 rxjs(forkjoin 或 mergemap)重构这段代码。我不确定如何实现。有人可以帮我弄这个吗?感谢任何帮助。
this.chapservice.cycle().subscribe((current) => {
this.selectedCycleId = current.ratingCycleId;
this.chapService
.getChapterEvalWithSkills(
this.activeUser.ipn,
this.selectedRatingCycleId
)
.subscribe((response) => {
console.log("response", response);
if (response && response.length > 0) {
this.chapterEvals = response;
}
});
this.chapservice
.getIsitEmployeeStatus(this.activeUser.ipn, this.selectedCycleId)
.subscribe((sdpStatus) => {
this.activeUserStatus = sdpStatus;
if (this.activeUserStatus.statusDescription == 'SUBMITTED') {
//do something
}
});
});
您必须使用 forkJoin
和 switchMap
的组合。
- 为什么
switchMap
? - 因为您有依赖值只能通过顺序执行来实现。
- 为什么
forkJoin
? - 您可以在此处使用 forkJoin
或 mergeMap
。
代码
this.chapservice.cycle().pipe(
switchMap((current: any) =>
forkJoin(
this.chapService.getChapterEvalWithSkills(
this.activeUser.ipn,
this.selectedRatingCycleId
),
this.chapservice.getIsitEmployeeStatus(this.activeUser.ipn, current.ratingCycleId)
)
)
).subscribe(([chapterEvals, sdpStatus]) => {
console.log(chapterEvals, sdpStatus);
if (chapterEvals && chapterEvals.length > 0) {
this.chapterEvals = chapterEvals;
}
this.activeUserStatus = sdpStatus;
if (this.activeUserStatus.statusDescription == 'SUBMITTED') {
//do something
}
});
});
在下面的代码中,我在订阅中使用了订阅。此代码有效,但代码结构非常糟糕。我想使用 rxjs(forkjoin 或 mergemap)重构这段代码。我不确定如何实现。有人可以帮我弄这个吗?感谢任何帮助。
this.chapservice.cycle().subscribe((current) => {
this.selectedCycleId = current.ratingCycleId;
this.chapService
.getChapterEvalWithSkills(
this.activeUser.ipn,
this.selectedRatingCycleId
)
.subscribe((response) => {
console.log("response", response);
if (response && response.length > 0) {
this.chapterEvals = response;
}
});
this.chapservice
.getIsitEmployeeStatus(this.activeUser.ipn, this.selectedCycleId)
.subscribe((sdpStatus) => {
this.activeUserStatus = sdpStatus;
if (this.activeUserStatus.statusDescription == 'SUBMITTED') {
//do something
}
});
});
您必须使用 forkJoin
和 switchMap
的组合。
- 为什么
switchMap
? - 因为您有依赖值只能通过顺序执行来实现。 - 为什么
forkJoin
? - 您可以在此处使用forkJoin
或mergeMap
。
代码
this.chapservice.cycle().pipe(
switchMap((current: any) =>
forkJoin(
this.chapService.getChapterEvalWithSkills(
this.activeUser.ipn,
this.selectedRatingCycleId
),
this.chapservice.getIsitEmployeeStatus(this.activeUser.ipn, current.ratingCycleId)
)
)
).subscribe(([chapterEvals, sdpStatus]) => {
console.log(chapterEvals, sdpStatus);
if (chapterEvals && chapterEvals.length > 0) {
this.chapterEvals = chapterEvals;
}
this.activeUserStatus = sdpStatus;
if (this.activeUserStatus.statusDescription == 'SUBMITTED') {
//do something
}
});
});