我刚开始使用ngRx,但遇到了一个小问题。
我想知道接口状态和模块forRoot
的键之间的区别。
export interface ConfigurationState {
readonly configuration: Configuration;
}
StoreModule.forRoot({
configuration: ConfigurationReducer,
}),
export function configurationReducer(state: Configuration = undefined, action: ConfigurationActions.Actions): Configuration {
switch (action.type) {
case ConfigurationActions.SET:
return action.payload;
default:
return state;
}
}
this.store.select('configuration')
当我选择带有第四段代码的商店时,我会看到关于第一段代码的键的智能帮助。
如果我更改第二段代码的键,它什么也不会改变。
所以我的问题是forRoot
的目的是什么?钥匙重要吗?
答案 0 :(得分:1)
接口的工作是类型检查和一些智能。 forRoot
是要注册您的减速器,这是最重要的部分,否则您的减速器将不会被调用。
在示例中,您发布的State
接口并没有真正添加任何值,但是如果您按照以下方式进行操作,则会添加一些类型检查值。
// reducer.ts
/**
* As mentioned, we treat each reducer like a table in a database. This means
* our top level state interface is just a map of keys to inner state types.
*/
export interface State {
layout: fromLayout.State;
router: fromRouter.RouterReducerState;
}
/**
* Our state is composed of a map of action reducer functions.
* These reducer functions are called with each dispatched action
* and the current or initial state and return a new immutable state.
*/
export const reducers: ActionReducerMap<State> = {
layout: fromLayout.reducer,
router: fromRouter.routerReducer,
};
// app.module.ts
StoreModule.forRoot(reducers),