状态更改时未调用 ngrx 存储订阅

ngrx store subscription not called when state changes

我正在使用在我的服务中定义的虚拟数据创建一个应用程序。

在一个组件中,我有以下删除产品的功能:

  removeItem(productId: string) {
      this.cartService.removeItem(productId);
  }

服务如下:

  removeItem(productId: string) {
    const itemIndex = this.cart.products.findIndex(el => el.id === productId);
    if (itemIndex > -1) {
      this.cart.products.splice(itemIndex, 1);
      return Observable.of(this.cart)
        .subscribe((cartResponse: Cart) => {
          this.store.dispatch({ type: CART_UPDATE, payload: cartResponse });
        });
    }
  }

(this.cart 是我在服务中硬编码的数据)。

我的减速器看起来像:

export const cartReducer = (state: Cart = {} as Cart, {type, payload}) => {
  switch (type) {

    case CART_UPDATE:
      // update categories state
      return payload;
    default:
      return state;
  }
};

然后我在一个组件中订阅购物车,例如:

  ngOnInit() {
    this.store.select('cart').subscribe((cart: Cart) => {
      console.log('here');
      this.numberOfItems = cart.products.length;
    });
  }

我也在app.module

StoreModule.provideStore({
  cart: cartReducer
}),

remove 函数工作正常,代码以正确的有效负载到达 reducer 函数。

问题是组件中的订阅回调仅在第一次加载组件时被调用。

当我调用 remove 函数时,产品确实被删除,reducer 函数被调用并返回正确的数据,但回调没有被调用。

我是不是漏掉了什么?

我认为问题在于您在 reducer 中返回的 payload 具有与现有状态相同的对象引用。尝试返回一个新对象并查看是否会导致调用您的订阅。像这样:

export const cartReducer = (state: Cart = {} as Cart, {type, payload}) => {
  switch (type) {    
    case CART_UPDATE:
      // update categories state
      return { ...payload }; // equivalent to Object.assign({}, payload);
    default:
      return state;
  }
};