首页 > 解决方案 > 行为主体在值变化时具有不同的发射计数

问题描述

我们在某些服务中有一个行为主题

  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时被调用两次!为什么它的值被发射了两次?他们不是有相同的代码吗?

标签: angularrxjs6

解决方案


问题是 fetchCategories 在城市值更改时被调用一次,而 fetchActiveCoupons 在城市值更改时被调用两次

它被调用了两次,因为它有两个订阅者。

您可以使用shareReplay()共享 observable 并重放先前的值

    this.activeCoupons = this.utilsService.cityObservable
    .pipe(
      debounceTime(100),
      switchMap(cityId => this.couponService.fetchActiveCoupons(cityId)),
      shareReplay(1)
    );

shareReplay()当您有大量的 observable 并希望与多个订阅者共享结果,或者您希望延迟订阅者接收以前的值时,您可以使用。


推荐阅读