angular - 行为主体在值变化时具有不同的发射计数
问题描述
我们在某些服务中有一个行为主题
city = new BehaviorSubject(config.defaultCity);
get cityObservable(){
return this.city.asObservable();
}
当我们在某个组件中获得 observable 时,我们可以监听值的变化,以便我们根据城市获取不同的数据。
像这样
categories: Observable<any>;
activeCoupons: Observable<any>;
ngOnInit() {
this.categories = this.utilsService.cityObservable
.pipe(
debounceTime(100),
switchMap(cityId => this.categoryService.fetchCategories(cityId)),
map((response: any) => response.data)
);
this.activeCoupons = this.utilsService.cityObservable
.pipe(
debounceTime(100),
switchMap(cityId => this.couponService.fetchActiveCoupons(cityId))
);
}
问题是fetchCategories
当城市价值改变时被调用一次,当城市价值改变fetchActiveCoupons
时被调用两次!为什么它的值被发射了两次?他们不是有相同的代码吗?
解决方案
问题是 fetchCategories 在城市值更改时被调用一次,而 fetchActiveCoupons 在城市值更改时被调用两次
它被调用了两次,因为它有两个订阅者。
您可以使用shareReplay()共享 observable 并重放先前的值
this.activeCoupons = this.utilsService.cityObservable
.pipe(
debounceTime(100),
switchMap(cityId => this.couponService.fetchActiveCoupons(cityId)),
shareReplay(1)
);
shareReplay()
当您有大量的 observable 并希望与多个订阅者共享结果,或者您希望延迟订阅者接收以前的值时,您可以使用。
推荐阅读
- mysql - 在 MySQL 计划事件中使用变量 OUTFILE
- electron - 无法在电子项目的 main.js 中使用 keytar
- 2d - 为什么透明像素在 WebGL 中不能正确混合
- c# - 如何在 ASP.NET Core 应用程序中的 Docker 上正确安装证书?
- python - 根据来自 cloudwatch 的维度子集获取结果
- ssl - HAproxy 在 TCP 模式下给出 PR_END_OF_FILE_ERROR
- python - 在哪里可以找到 GIMP Python Object References,我目前正在寻找 Vectors 和 Points 的属性
- python - 我正在使用 Pandas 和 BeautifulSoup 抓取足球名单,但它未能抓取两列
- c# - ASP.NET MVC & Ajax json Datatables 错误 - json 错误,单元格不显示数据
- flutter - html代码作为单引号内的字符串双引号