angular - Angular 使用带有 BehaviorSubject 和 ExhaustMap 的 NgBusy
问题描述
将ng-busy与更复杂的 RxJS 运算符(如switchMap
或exhaustMap
在 a 上)一起使用时,最佳实践是什么BehaviorSubject
?
如果你设置 this.busy ,BehaviorSubject
它总是很忙,因为它关闭了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) => { ... }
);
正如我从这样的文章中了解到的,以下代码在使用 observables 时不是最佳实践,但我不知道该怎么做。
但这就像 Observableception,对吧?不,Observables 不喜欢在 Observables 中。
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) => { ... }
);
推荐阅读
- python - 类型的无效输入:“产品”。先转换为字节、字符串、整数或浮点数
- elasticsearch - 弹性搜索。具有大量映射的单个索引与具有少量映射的多个索引
- google-chrome - 如何在domready之前在webview电子中永久禁用滚动条
- networking - 将 Sharepoint 映射为网络驱动器失去连接
- windows - 拦截或读取 Windows 推送通知
- html - 如何使用 CSS 为 body 和 boder 设置不同的不透明度?
- css - CSS 关键帧动画名称
- javascript - 需要 JavaScript 才能通过电子邮件传递 URL 地址,该地址将链接到打开特定模式的登录页面
- javascript - 笑话/酶 expect.any(ReactComponent)
- sql - 从 SELECT 语句中导出数据