angular - 我无法正确共享我的 Observable 流并且我的 http 请求调用了两次
问题描述
嘿,我对共享运营商有疑问。当我使用带有 data$ 和 totalElements$ 的异步管道时,我的 http 请求执行了两次。我希望它只执行一次。我尝试使用 shareReplay ,但效果不佳。
filters$: BehaviorSubject<any> = ...
...
getComplaints() {
return this.filters$.pipe(
flatMap(filters => {
this.loading = true;
return this.complaintService
.getComplaints$(filters)
.pipe(
finalize(() => this.loading = false),
share()
);
})
);
}
this.data$ = this.getComplaints().pipe(map(value => value.pageItems));
this.totalElements$ = this.getComplaints().pipe(map(value => value.totalItems));
解决方案
为了share
工作,您必须只创建一个可观察对象(所以不要使用函数)并将运算符放在外部可观察对象上。您可能希望使用shareReplay
以便迟到的订阅者获得最新的价值。
this.complaints$ = this.filters$.pipe(
flatMap(filters => {
this.loading = true;
return this.complaintService
.getComplaints$(filters)
.pipe(
finalize(() => this.loading = false),
);
}),
shareReplay(1)
);
this.data$ = this.complaints$.pipe(map(value => value.pageItems));
this.totalElements$ = this.complaints$.pipe(map(value => value.totalItems));
推荐阅读
- python - 读取具有 key="value" 格式的文本数据文件的最佳方法?
- firefox - Nuxt Firefox 滚动到页面底部
- .htaccess - 虽然我使用 .htaccess,但我的反应应用程序的链接不起作用
- amazon-web-services - Terraform aws_codebuild_project 错误:InvalidInputException:
- python - 通过执行更改的 Python 脚本
- node.js - 将 EventEmitter 与 NodeJ 和 Azure 函数一起使用
- amazon-web-services - 更新 ECS 服务任务定义时跟踪状态
- sql - SQL 查询返回带和不带空格的结果
- python - 如何获取与熊猫中的多列分组相关的所有值
- python-3.x - 有没有办法像在 shell 中一样使用 Python 中最后输入的输入?