2017-06-12 459 views
1

我幾乎是一個redux模式的新手,並剛剛開始使用ngrx。這真棒,這是我想盡可能使用的東西,但我有幾個關於Store概念的問題。商店vs商店<T>

我會嘗試通過幾個示例來描述問題,並在本帖末尾提問我的問題。

讓我們先從AppState接口和減速器:

export interface AppState{ 
    people: Person[], 
    events: Event[] 
} 

//events reducer 
export function eventsReducer(state: any = {}, {type, payload}): Event[]{ 
    switch(type){ 
    case "ADD_EVENT": 
     return [...state, payload]; 
    default: 
     return state; 
    } 
} 

//people reducer 
export function peopleReducer(state: any = {}, {type, payload}): Person[]{ 
    switch(type){ 
    case "ADD_PERSON": 
     return [...state, payload]; 
    default: 
     return state; 
    } 
} 

//root reducer 
const root: ActionReducer<AppState> = combineReducers({people: peopleReducer, events: eventsReducer}); 
const INITIAL_STATE = { 
    people:[], 
    events: [] 
} 
export function rootReducer(state: any = INITIAL_STATE, action: any){ 
    return root(state, action); 
} 

rootReducer加入這樣的:

//part of the AppModule 
... 
imports:[ 
..., 
StoreModule.provideStore(rootReducer) 
] 

,並在主AppComponent這裏是如何我accesing的store

//part of the AppComponent 
export class AppComponent{ 
    people: Observable<Person[]>; 
    events: Observable<Event[]>; 

    constructor(private store: Store<AppState>){ 
     this.people = store.select('people'); 
     this.events = store.select('events'); 
    } 
} 

現在,一切我很喜歡這個概念,但我注意到,如果我從AppState界面刪除其中一個屬性(例如,我刪除了people屬性,其他所有內容保持不變),則沒有任何更改(或中斷)。

所以我想知道有Store<AppState>,而不是僅僅Store主要的原因是什麼,什麼是使用Store<AppState>(它實際上取得對抗只是用Store差異)的主要優勢是什麼?另外,是否有一種方法可以在AppState更改時至少執行運行時錯誤,但其他所有內容都保持不變?

我使用錯誤的可能性也非常高,但我仍然想知道這些問題的答案。

回答

1

商店的select method可以傳遞一個或多個屬性字符串或選擇器函數。

當傳遞屬性字符串時,它的行爲如同pluck。當通過選擇器功能時,它的行爲如同map

這些之間的顯着差異是傳遞給pluck的屬性路徑無法進行類型檢查,並且pluck返回Observable<any>,因此狀態的類型信息基本上丟失。

如果使用選擇功能,相反,你會看到打字稿錯誤,遺漏屬性等

例如,這樣的:

store.select(state => state.missing); 

會影響一個錯誤,而這不會:

store.select('missing'); 
+0

感謝您的回答。我一直在研究'Store '實現中''T'的功能,但從來沒有打算檢查'select'方法。 – eminlala