我有一个商店状态:
export interface DocumentState {
document: Document;
selectedPage: number;
}
我想打电话给DoSomethingOnlyOnDocumentChange(doc: Document)
和DoSomethingOnlyOnPageChange(Document: doc, page: number)
。我们的想法是不要在其他状态变化上执行处理程序。我订阅了状态更改,如下所示:
this.store$.select(appState => appState.documentState.document).subscribe(this.DoSomethingOnlyOnDocumentChange);
this.store$.select(appState => appState.documentState.selectedPage).subscribe(this.DoSomethingOnlyOnPageChange);
如何在页面更改状态处理程序中访问文档?
这就是ngrx selectors
存在的原因。
首先为您需要的状态切片创建一个选择器:
export const selectDocument = createFeatureSelector<AppState,
DocumentState>('document');
export const getDocument = createSelector(
selectDocument,
(state: DocumentState) => state.document
);
然后在您的组件中使用它:
this.store$.select(getDocument).subscribe(this.DoSomethingOnlyOnDocumentChange);
这样,只有对文档切片所做的更改才会由DoSomethingOnlyOnDocumentChange
处理