我该如何摆脱这些嵌套订阅?我想使用 concatMap 或 mergeMap 来做到这一点 - 如果您同意,我如何处理与外部订阅不同的内部订阅的 takeUntil ?我对操作符和 RxJ 还很陌生。
this.myService.selectedCustomerId
.pipe(
takeUntil(this.unsubscribe),
).subscribe((customerId: number) => {
// Do some stuff...
this.anotherService.hasPermission("ROLE1", customerId).pipe(
takeUntil(this.cancel),
).subscribe(hasPermission => this.hasPermissionForRole1 = hasPermission);
this.anotherService.hasPermission("ROLE2", customerId).pipe(
takeUntil(this.cancel),
).subscribe(hasPermission => this.hasPermissionForRole2 = hasPermission);
this.anotherService.hasPermission("ROLE3", customerId).pipe(
takeUntil(this.cancel),
).subscribe(hasPermission => this.hasPermissionForRole3 = hasPermission);
}
);
Run Code Online (Sandbox Code Playgroud)
你可以这样实现:
this.myService.selectedCustomerId
.pipe(
takeUntil(this.unsubscribe),
mergeMap(customerId: number) => {
const roles = ["ROLE1", "ROLE2", "ROLE3"];
return forkJoin(
roles.map(role => this.anotherService.hasPermission(role, customerId))
)
}
).subscribe(([role1, role2, role3]) => {
// Do some stuff...
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
700 次 |
| 最近记录: |