我目前正在研究使用 ngrx 商店(v. 4.0.3)进行状态管理。这似乎是一个伟大的项目。
在尝试初始化商店状态时,我遇到了一些障碍。该文档使它看起来相当简单,但我无法看到我哪里出错了。
以下是相关的代码片段:
在 app.state.ts
export interface AppState {
searchText: string;
}
在 search-text.reducer.ts
export const UPDATE = 'UPDATE';
export class UpdateSearchTextAction implements Action {
readonly type: string = UPDATE;
constructor(public readonly text: string) {}
}
export function searchTextReducer(state: string, action: UpdateSearchTextAction) {
switch(action.type) {
case UPDATE:
return action.text;
}
};
在 app.module.ts
export const reducers: ActionReducerMap<AppState, UpdateSearchTextAction> = {
searchText: searchTextReducer
};
export const initialState: InitialState<AppState> = {
searchText: 'sds'
};
....
imports: [
....
StoreModule.forRoot(reducers, initialState)
]
在某些组件中
constructor(private store: Store<AppState>) {
this.searchBoxText = store.select('searchText');
this.searchBoxText.subscribe(text => console.log('value = [' + text + "]"));
}
因此,当应用程序加载时,我希望看到以下记录到控制台:
value = [sds]
但我看到
value = [undefined]
稍后,一旦我开始输入触发 UpdateSearchTextAction 的输入,控制台确实会记录正确的值。所以看起来我已经正确设置了商店。
我可能缺少一些真正简单的东西。任何人都可以提供一些建议吗?