angular - 无法从商店 ngrx 获取值
问题描述
我面对的是 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 Action] 添加 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
怎么可能?
解决方案
国家是
export interface IdState {
id: any;
}
因此选择器应该从其特征状态中选择 id
export const selectIdValue = createSelector(
selectIdState,
state => state.id, // selectIdState returns an object of IdState interface.
);
然后,reducer,它应该将id
prop 添加到 state,而不是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'}));
如果你有这样的事情 - 它应该工作。如果您有更多问题,请告诉我。
推荐阅读
- python - 比较两个数据帧的值
- mysql - Mysql 计算多个 SUM() 变量
- python - 有没有办法使用 Sphinx (autodoc) 显示 Snakefile 的文档字符串?
- java - 选择按钮的 Xpath
- reactjs - 切换到另一个页面后,componentWillUnmount 工作
- reactjs - 在这个基于 React 的表单中,我对 `setValues` 发生的事情感到困惑。你能帮忙详细说明一下吗?
- hadoop - Hive JMX 指标启用
- java - 覆盖超级方法时的 ClassCastException(可比较
) - sql - 当引号中有数字或混合数据时如何正确确定数据类型?
- r - 未找到带有 GWmodel 对象的闪亮应用