Angular 商店vs商店<;T>;
我是Angular 商店vs商店<;T>;,angular,ngrx,ngrx-store,Angular,Ngrx,Ngrx Store,我是redux模式的新手,刚刚开始使用ngrx。这非常棒,我希望尽可能多地使用它,但我有几个关于商店概念的问题 我将试着通过几个例子来描述这个问题,并在这篇文章的结尾问我的问题 让我们从AppState接口和减缩器开始: export interface AppState{ people: Person[], events: Event[] } //events reducer export function eventsReducer(state: any = {}, {type
redux
模式的新手,刚刚开始使用ngrx
。这非常棒,我希望尽可能多地使用它,但我有几个关于商店
概念的问题
我将试着通过几个例子来描述这个问题,并在这篇文章的结尾问我的问题
让我们从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);
}
在主AppComponent
中,我是如何访问存储的:
//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');
}
}
//AppComponent的一部分
导出类AppComponent{
人:可观察的;
事件:可观察;
构造函数(私有存储:存储){
this.people=store.select('people');
this.events=store.select('events');
}
}
现在,一切正常,我非常喜欢这个概念,但我注意到,如果我从AppState
界面中删除其中一个属性(例如,我删除people
属性,其他所有属性都保持不变),则不会发生任何更改(或中断)
因此,我想知道使用Store
而不仅仅是Store
的主要原因是什么,以及使用Store
的主要优势是什么(实际上,使用Store
与使用Store
有什么不同)?另外,是否有一种方法可以在AppState更改时至少强制执行运行时错误,但其他所有操作都保持不变
我错误使用它的可能性也很高,但我仍然想知道这些问题的答案。可以向商店传递一个或多个属性字符串或选择器函数
当传递属性字符串时,其行为类似于。当传递选择器函数时,其行为类似于
这两者之间的显著区别在于,传递给pulk
的属性路径无法进行类型检查,pulk
返回可观察的
,因此状态的类型信息基本上丢失
如果使用选择器函数,则会看到缺少属性等的TypeScript错误
例如,这:
store.select(state=>state.missing);
将产生错误,但不会:
store.select('missing');
谢谢您的回答。我一直在研究它在Store
实现中对T
的作用,但从未检查过select
方法。
//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');
}
}