我正在使用我的服务中定义的虚拟数据创建一个应用程序。
在一个组件中,我具有以下删除产品的功能:
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函数被调用并返回正确的数据,但回调没有被调用。
我错过了什么吗?