Ngrx存储:使用额外数据对特定切片更改执行选择处理程序

问题描述 投票:-1回答:1

我有一个商店状态:

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

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

angular ngrx-store
1个回答
0
投票

这就是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 documentation

© www.soinside.com 2019 - 2024. All rights reserved.