商店与商店<t>

时间:2017-06-12 23:41:16

标签: angular ngrx ngrx-store

我几乎是redux模式的新手,刚刚开始使用ngrx。它太棒了,我想尽可能多地使用它,但我对Store概念有几个问题。

我将尝试通过一些示例来描述问题,并在本文末尾提出我的问题。

让我们从AppState界面和reducers开始:

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以下是我访问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 个答案:

答案 0 :(得分:1)

商店的select method可以传递一个或多个属性字符串或选择器函数。

传递属性字符串时,其行为类似于pluck。当传递选择器函数时,它的行为类似于map

这些之间的显着差异是传递给pluck的属性路径无法进行类型检查,pluck返回Observable<any>,因此状态的类型信息基本上丢失了。 / p>

如果使用选择器功能,则会看到缺少属性的TypeScript错误等。

例如,这个:

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

会影响错误,而这不会:

store.select('missing');
相关问题