Angular Using NgBusy with a BehaviorSubject and ExhaustMap



当将ng-busy 与更复杂的 RxJS 运算符(如switchMapBehaviorSubjectexhaustMap(一起使用时,最佳实践是什么?

如果您在BehaviorSubject上设置 this.busy 它将始终处于繁忙状态,因为它将关闭BehaviorSubject而不是 Http 请求订阅。

public currentPage$ = new BehaviorSubject(1);
// ...
// Not sure how to use "busy" this way:
this.currentPage$
.pipe(
exhaustMap((page: number = 1) =>
(page) ? this.getAlerts(page) : empty()
),
map((response: HttpResponse<Alert[]>) => 
response.results
)
)
.subscribe(
(alerts: Alert[]) => { ... },
(error: any) => { ... }
);

正如我从这样的文章中了解到的那样,下面的代码不是使用可观察量的最佳实践,但我看不出还能怎么做。

但这就像可观察感知,对吧?不。可观察量不喜欢 在可观察量内部。

this.currentPage$
.subscribe(
(page: number = 1) => {
// Can use "busy" this way:
this.busy = this.getAlerts(page)
.pipe(
map((response: HttpResponse<Alert[]>) => 
response.results
)
)
.subscribe(
(alerts: Alert[]) => { ... },
(error: any) => { ... }
);
},
(error: any) => { ... }
);

如果您希望在管道流中触发副作用,tap运算符是 goto:

this.currentPage$.pipe(
exhaustMap((page: number = 1) => { 
if(page) {
const obs$ = this.getAlerts(page).pipe(share());
this.busy = obs$.subscribe();
return obs$;
} else
return empty();
}),
map((response: HttpResponse<Alert[]>) => response.results),
).subscribe(
(alerts: Alert[]) => { ... },
(error: any) => { ... }
);

最新更新