我正在使用我的服务中定义的虚拟数据创建一个应用程序.
在一个组件中,我有以下删除产品的功能:
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中返回的有效负载与现有状态具有相同的对象引用.尝试返回一个新对象,看看是否会导致您的订阅被调用.像这样:
export const cartReducer = (state: Cart = {} as Cart,payload}) => { switch (type) { case CART_UPDATE: // update categories state return { ...payload }; // equivalent to Object.assign({},payload); default: return state; } };