【发布时间】:2017-08-25 13:38:20
【问题描述】:
我目前正在研究使用 ngrx 存储 (v. 4.0.3) 进行状态管理。这似乎是一个很棒的项目。
我在尝试初始化商店的状态时遇到了一些障碍。 documentation 让它看起来很简单,但我看不到哪里出错了。
这里是相关代码sn-ps:
在 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 的输入,控制台确实会记录正确的值。所以看来我已经正确设置了商店。
我可能缺少一些真正简单的东西。谁能给点建议?
【问题讨论】: