状态更改时未调用ngrx存储订阅 [英] ngrx store subscription not called when state changes

查看:52
本文介绍了状态更改时未调用ngrx存储订阅的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am creating an application with dummy data defined in my service.

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

In one component, I have the following function that deletes a product:

  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是我在服务中硬编码的数据).

(this.cart is the data I have hard coded in the service).

我的减速器看起来像:

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

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

然后我将购物车订购为一个组件,例如:

Then I am subscribing to the cart in one component like:

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

我也有app.module

I also have in app.module

StoreModule.provideStore({
  cart: cartReducer
}),

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

The remove function works fine, and the code reaches the reducer function with the correct payload.

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

The issue is that the subscription callback in the component is called only the first time the component is loaded.

当我调用remove函数时,确实删除了产品,并调用了reducer函数并返回了正确的数据,但未调用回调.

When I call the remove function, the product is indeed removed and the reducer function is called and returning the correct data, but the callback is not called.

我想念什么吗?

推荐答案

我认为问题在于您在化简器中返回的payload具有与现有状态相同的对象引用.尝试返回一个新对象,看看是否导致您的订阅被调用.像这样:

I think the issue is that the payload you are returning in the reducer has the same object reference as the existing state. Try returning a new object and see if that causes your subscription to be invoked. Like so:

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;
  }
};

这篇关于状态更改时未调用ngrx存储订阅的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆