Angular 2 如何防止订阅触发,除非 map 返回的两个值中的任何一个发生变化

Angular 2 how to prevent subscribe from firing unless the either of the two values returned by map has changed

我发现了一个不太容易解决的简单问题,我试图让订阅不触发,除非这两个值中的任何一个 sorting.changespagination.changes 已改变。我猜 distinctUntilChanged 应该被使用,但是我不知道应该提供什么作为它的参数,因为我有两个值需要检查而不是一个。

编辑(这次是正确的订阅调用): 这是订阅调用:

this.requestParamsSubscription = this.store.select('brands')
  .distinctUntilChanged()
  .map((brands: IBrandsStorage) => {
    return {sorting: brands.sorting, pagination: brands.pagination};
  })
  .subscribe(
    params => {
      this.store.dispatch({type: BrandsActions.GET_BRANDS_REQUEST});
    }
  );

changes of the objects 是一个简单的数字计数器,它跟踪变化,我想我可以用它来检查自上次以来对象是否发生了变化。

有什么想法吗?

distinctUntilChanged 可以传递一个比较函数(如果参数不变,应该 return true)。如果必须更改 alltotal,您可以使用:

this.brandsStorageSubscription = this.store.select('brands')
  .map((brands: IBrandsStorage) => ({ all: brands.all, total: brands.total }))
  .distinctUntilChanged((a, b) => (a.all === b.all) && (a.total === b.total))
  .subscribe(
    brands => {
      console.log(brands);
      this.total = brands.total;
      this.brands = brands.all;
    }
  );