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

cal*_*ack 6 ngrx angular ngrx-store

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

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

  removeItem(productId: string) {
      this.cartService.removeItem(productId);
  }
Run Code Online (Sandbox Code Playgroud)

和服务如下:

  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 });
        });
    }
  }
Run Code Online (Sandbox Code Playgroud)

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

我的减速机看起来像:

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

    case CART_UPDATE:
      // update categories state
      return payload;
    default:
      return state;
  }
};
Run Code Online (Sandbox Code Playgroud)

然后我订购了一个组件中的购物车,如:

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

我也有app.module

StoreModule.provideStore({
  cart: cartReducer
}),
Run Code Online (Sandbox Code Playgroud)

remove函数工作正常,代码使用正确的有效负载到达reducer函数.

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

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

我错过了什么吗?

Ted*_*rne 12

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

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;
  }
};
Run Code Online (Sandbox Code Playgroud)

  • 这挽救了我的生命.几个小时都在苦苦挣扎,想知道为什么它不起作用 (2认同)