首页 > 解决方案 > Ngrx 存储:使用额外数据对特定切片更改执行选择处理程序

问题描述

我有一个商店状态:

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);

如何在页面更改状态处理程序中访问文档?

标签: angularngrx-store

解决方案


这就是存在的理由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

参考:ngrx 文档


推荐阅读