I am creating an application with dummy data defined in my service.
In one component, I have the following function that removes a product:
removeItem(productId: string) {
this.cartService.removeItem(productId);
}
and service:
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 is the data that I hardcoded in the service).
My gearbox is as follows:
export const cartReducer = (state: Cart = {} as Cart, {type, payload}) => {
switch (type) {
case CART_UPDATE:
return payload;
default:
return state;
}
};
Then I subscribe to the cart in one component, for example:
ngOnInit() {
this.store.select('cart').subscribe((cart: Cart) => {
console.log('here');
this.numberOfItems = cart.products.length;
});
}
I also have in app.module
StoreModule.provideStore({
cart: cartReducer
}),
The delete function works fine, and the code reaches the reducer function with the correct payload.
The problem is that the subscription callback in the component is called only when the component is first loaded.
When I call the remove function, the product is really removed and the reducer function is called and returns the correct data, but the callback is not called.
Did I miss something?