我有幾個子商店。比方說Sub1
和Sub2
以下狀態和減速器(行動並不是我的問題有趣......我猜的):ngrx/store 4:從商店選擇時得到意外的子狀態
Sub1的:
export interface Sub1State {
sub1value: string
}
export function sub1reducer(state: Sub1State, action: Action): Sub1State {
...
}
分公司2:
export interface Sub2State {
sub2value: number
}
export function sub2reducer(state: Sub2State, action: Action): Sub2State {
}
然後我將這兩個子狀態合併爲一個ActionReducerMap<ApplicationState>
:
export interface ApplicationState {
sub1: Sub1State,
sub2: Sub2State
}
export const reducers: ActionReducerMap<ApplicationState> = {
sub1: sub1reducer,
sub2: sub2reducer
};
和「註冊」它的商店:
StoreModule.forRoot(reducers)
現在,在一個角度分量,我想選擇Sub1
店,並獲得sub1value
字符串。所以我做...
sub1value$: Observable<string>;
constructor(private store: Store<Sub1State>) {
this.sub1value$ = store.map(state => {
console.log(state);
return state.sub1value;
});
}
在日誌中陳述,我希望得到以下對象(Sub1State對象):
{
sub1value: 'initial value'
}
但我真正得到的是這個對象:
{
sub1: {
sub1value: 'initial value'
}
}
這是按照預期工作嗎?如果是的話,我應該如何使用接口Sub1State?因爲sub1
不是界面的一部分。
而且還好奇的是,呼籲state.sub1value
什麼顯然是錯誤的,因爲它必須是state.sub1.sub1value
當我沒有得到任何錯誤(沒有編譯器錯誤,也沒有運行時錯誤)。沒有運行時錯誤我明白,這是簡單的未定義。但在我看來,TypeScript編譯器應該在這裏拋出一個錯誤。
我真的很困惑:/
編輯
這裏是我怎麼會想到一個例子它的工作原理:https://stackblitz.com/edit/angular-w34kua?file=app%2Fapp.component.ts
但如何再選擇功能正常工作?我在大多數例子中看到了像'getValue1(state:Sub1State):string'這樣的簽名。但是,如果我將此選擇器函數傳遞給'store.select(getValue1)',它將不起作用,因爲傳遞給選擇器函數的對象不是「Sub1State」類型,而是「sub1」根元素。另外一個具有子狀態的商店被注入'構造函數(private store:Store)'。 –
如果你按照我描述的方式做,你會得到sub1狀態。做store.select('sub1')。訂閱(.......)。這會給你sub1狀態對象 – Kevin
好吧,對,這是有效的。但如果我這樣做,我也可以寫一個簡單的服務,我必須手動訂閱和取消訂閱。我失去了Flux/Redux/Store架構的一些很酷的功能。但我不想手動訂閱和取消訂閱,我只想分享應用程序狀態並將其保存在本地可觀察項中。以下是我期望能夠工作的一個示例,但不起作用:https://stackblitz.com/edit/angular-w34kua?file=app%2Fapp.component.ts –