我正面临NgRx,我不明白如何很难向商店添加值并检索它。无论如何,那是我到目前为止所做的
效果ts:
export class idEffects {
saveId$ = createEffect(() =>
this.actions$
.pipe(
ofType(idActions.addIdAction),
tap(payload => {
console.log("action",payload);
})
)
,{dispatch: false});
constructor(
private actions$: Actions
) {}
}
动作ts:
export const ADD_ID ='[Id操作]添加ID';
export const addIdAction = createAction(
ADD_ID,
props<{id: any}>()
)
减速器ts:
export interface IdState {
id: any;
}
export const defaultId: IdState = {
id: undefined
};
export const idReducer = createReducer (
defaultId,
on(idActions.addIdAction, (state, action) => {
//console.log("Calling id reducer", action);
return {
id: action
}
})
)
和选择器ts:
export const selectIdState =
createFeatureSelector<IdState>("id")
export const selectIdValue = createSelector(
selectIdState,
id => id
);
现在,这就是我的app.module.ts
StoreModule.forRoot({id: idReducer}),
EffectsModule.forRoot([IdEffects]),
StoreModule.forRoot(reducers, {
metaReducers
}),
StoreDevtoolsModule.instrument({maxAge: 25}),
StoreRouterConnectingModule.forRoot({
stateKey: 'router',
routerState: RouterState.Minimal
})
似乎存储数据工作良好,因为控制台中的Redux面板返回以下内容:
id(pin):"1"
data(pin):"Hello There"
type(pin):"[Id Action] add id"
但是,当我尝试检索该对象时,我得到一个undefined
,并以此方式进行操作:
this.id$ = storeId.pipe(select(selectIdValue))
和html
<h4>The id obj is: {{id$ | async}}</h4>
但是它什么也没写。我尝试使用该组件中的订阅来获取结果,这使我undefined
变得可能吗?
答案 0 :(得分:1)
状态是
export interface IdState {
id: any;
}
因此选择器应从其功能状态中选择ID
export const selectIdValue = createSelector(
selectIdState,
state => state.id, // selectIdState returns an object of IdState interface.
);
然后,化简器应将id
道具添加到状态,而不是action
on(idActions.addIdAction, (state, action) => {
//console.log("Calling id reducer", action);
return {
...state, // not needed in your case, but a good style.
id: action.id, // <- .id
}
}),
效果,不需要它,您可以将其删除。
,最后是reducers
变量。您可以分享其来源吗?
应该是
const reducers = {
id: idReducer, // id key is important, idReducer is enough for now.
};
也不要忘记在addIdAction
某处派遣。
例如在组件的ngOnInit
中。
this.store.dispatch(addIdAction({id: 'value'}));
如果您有类似的事情-应该可以。 如果您还有其他问题,请告诉我。