RxJs Observables 嵌套订阅与 takeUntil
RxJs Observables nested subscriptions with takeUntil
我应该如何摆脱这些嵌套订阅?我想使用 concatMap 或 mergeMap 来做到这一点 - 如果你同意,我如何处理内部订阅与外部订阅不同的 takeUntil?我对运算符和 RxJs 很陌生。
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);
}
);
你可以这样实现:
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...
}
我应该如何摆脱这些嵌套订阅?我想使用 concatMap 或 mergeMap 来做到这一点 - 如果你同意,我如何处理内部订阅与外部订阅不同的 takeUntil?我对运算符和 RxJs 很陌生。
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);
}
);
你可以这样实现:
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...
}