【问题标题】:ngrx store subscription not called when state changes状态更改时未调用 ngrx 商店订阅
【发布时间】:2018-02-16 07:32:35
【问题描述】:

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

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

  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函数被调用并返回正确的数据,但没有调用回调。

我错过了什么吗?

【问题讨论】:

    标签: angular ngrx ngrx-store


    【解决方案1】:

    我认为问题在于您在 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;
      }
    };
    

    【讨论】:

    • 您能否进一步解释一下payload如何具有与状态相同的对象引用?
    • 在 cartService 中有一个对当前状态的引用。您正在对其进行变异,然后将其发送到减速器,因此对象引用永远不会改变。我建议您从组件中分派事件,删除服务,然后删除产品并从减速器内部返回新版本的状态
    • 这救了我的命。挣扎了几个小时想知道为什么它不起作用
    • Ty,为此苦苦挣扎了一个小时
    猜你喜欢
    • 2022-10-21
    • 1970-01-01
    • 2019-03-06
    • 2019-12-03
    • 2019-08-18
    • 1970-01-01
    • 1970-01-01
    • 2020-03-26
    • 1970-01-01
    相关资源
    最近更新 更多