我目前正在考虑使用ngrx存储(v。4.0.3)进行状态管理。这似乎是一个伟大的项目。无法初始化ngrx(v。4.x)存储的状态
我试图初始化我的商店的状态时,在路上碰到了一点碰撞。 documentation使它看起来很简单,但我不能看到我要去哪里错了。
下面是相关的代码片段:
在app.state.tsexport interface AppState {
searchText: string;
}
在搜索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的输入中,控制台确实记录了正确的值。因此,我似乎已经正确设置了商店。
有可能是真的很简单,我错过了。任何人都可以提供建议吗?
您的建议是我一直在做的事情,但只是为了响应用户输入。我试图弄清楚的是,如何设置AppState的初始状态而不分配Action。由于StoreModule.forRoot的签名需要一个reducer和一个StoreConfig,我认为它可以用来初始化状态,所以我很茫然。我不想要的是,我店里的所有状态都是用undefined初始化的。 –