我目前正在考慮使用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初始化的。 –