为什么我的 Angular ngrx 没有按预期将数据存储到商店并从商店检索数据?
Why is my Angular ngrx not storing data to and retrieving it from the store as expected?
我的reducer注册在index.ts的reducer常量中,如图:
export const reducers: ActionReducerMap <State> = {
homeState:HomeReducers,
productsState:ProductsReducers
}
reducers 被导入到 app.module 中,如图所示:
@NgModule({
declarations: [
AppComponent
],
imports: [
StoreModule.forRoot(reducers, {}),
],
})
export class AppModule { }
我的动作函数如下图:
export const StoreProducts = createAction(
'[Store Products] Store Products',
props<{products}>()
)
动作函数调用如图:
this.httpClient.get(`${this.url}/${queryParams}`).pipe(
tap(products => {
console.log('ProductsService products', products)
productsActions.StoreProducts({products})
})
).subscribe();
此处显示了预期用于存储数据的减速器:
export const ProductsReducers = createReducer(initialState,
on(productsActions.StoreProducts, (state, action) => {
console.log('action.products', action.products)
return {
...state, products: action.products
}
}),
)
数据永远不会到达商店。我已经实施了其他几个工作正常的减速器。
是否可以在action函数中写调试语句?
NgRx
中的 Action
应该使用 store.dispatch 函数调度,而不是直接调用它。
所以你可以像下面这样调整你的代码:
constructor(private store: Store) {}
//...
this.httpClient
.get(`${this.url}/${queryParams}`)
.pipe(
tap((products) => {
console.log('ProductsService products', products);
// >>>> You can dispatch the any NgRx's actions using store.dispatch function <<<<<
this.store.dispatch(productsActions.StoreProducts({ products }));
})
)
.subscribe();
}
我的reducer注册在index.ts的reducer常量中,如图:
export const reducers: ActionReducerMap <State> = {
homeState:HomeReducers,
productsState:ProductsReducers
}
reducers 被导入到 app.module 中,如图所示:
@NgModule({
declarations: [
AppComponent
],
imports: [
StoreModule.forRoot(reducers, {}),
],
})
export class AppModule { }
我的动作函数如下图:
export const StoreProducts = createAction(
'[Store Products] Store Products',
props<{products}>()
)
动作函数调用如图:
this.httpClient.get(`${this.url}/${queryParams}`).pipe(
tap(products => {
console.log('ProductsService products', products)
productsActions.StoreProducts({products})
})
).subscribe();
此处显示了预期用于存储数据的减速器:
export const ProductsReducers = createReducer(initialState,
on(productsActions.StoreProducts, (state, action) => {
console.log('action.products', action.products)
return {
...state, products: action.products
}
}),
)
数据永远不会到达商店。我已经实施了其他几个工作正常的减速器。 是否可以在action函数中写调试语句?
NgRx
中的 Action
应该使用 store.dispatch 函数调度,而不是直接调用它。
所以你可以像下面这样调整你的代码:
constructor(private store: Store) {}
//...
this.httpClient
.get(`${this.url}/${queryParams}`)
.pipe(
tap((products) => {
console.log('ProductsService products', products);
// >>>> You can dispatch the any NgRx's actions using store.dispatch function <<<<<
this.store.dispatch(productsActions.StoreProducts({ products }));
})
)
.subscribe();
}