2017-05-06 65 views
2

我对每个reducer的单个状态如何分片有一些疑问。 在大量的在线教程中(如this one),手动定义了一个根全局状态,该状态组合了称为AppState的所有单个状态。NgRx - 状态如何分片

它是正确的说,当我们通过一个包含所有减速到StoreModule对象字面:

StoreModule.provideStore({r1: ReducerFunc1, r2: ReducerFunc2, ...}) 

的对象键r1r2可用于使用字符串选择时要查询状态的切片:

store.select("r1") 

然而,如果我们想要的类型安全,我们定义届时AppState接口,并确保该对象键传递给NGRX减速对象文本的对象键相匹配,这样我们就可以使用store.select(appstate => appstate.r1)(并且这是AppState接口的唯一有用的例子)?

回答

2

为了有型的安全设置它是这样的:

export interface AppState { 
    auth: AuthState; 
    contacts: ContactsState; 
    events: EventsState; 
} 

每片将有它自己的界面。

然后您设置减速

export const reducers: ActionReducerMap<AppState> = { 
    auth: fromAuth.reducer; 
    contacts: fromContacts.reducer; 
    events: fromEvents.reducer; 
} 
您的应用程序模块中

然后

imports: [ 
    StoreModule.forRoot(reducers), 
], 

你AUTH减速,例如,将像

export function reducer(state: AuthState = initialAuthState, 
         action: Action) { 

这等定义每个reducer都由它的关键字,auth reducer和auth状态来调用。

+0

只有几行很好的信息。谢谢! – hgoebl

0

我想你必须设置AppState接口。例如,当你的依赖注入的商店,你可以这样做:

constructor(private store: Store) 

店里已经采取的接口,像这样:

constructor(private store: Store<AppState>) 

既然你必须指定届时AppState你可能想总是使用胖箭头函数来获取AppState切片,因为您获得了类型安全性。

store.select(appstate => appstate.r1)