3
我正在使用服務中定義的虛擬數據創建應用程序。狀態更改時不調用ngrx商店訂閱
在一個組分,我有以下功能刪除產品:
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函數並返回正確的數據,但未調用回調函數。
我錯過了什麼嗎?
請問請進一步解釋一下負載如何具有與狀態相同的對象引用? – callback
在cartService中,您可以參考當前狀態。您正在對它進行變異,然後將其發送給reducer,以便對象引用永遠不會改變。我建議你從組件派遣事件,刪除服務,並刪除產品,並從還原器中返回新版本狀態 –
這已挽救了我的生命。一直苦苦掙扎幾個小時,想知道爲什麼它不工作 – suku