Ngrx:结合两个选择器

Jor*_*rdi 5 ngrx

我建立了这个IStore

export interface IStore {
  user: IUser;
  sources: ISourceRedux;
}
Run Code Online (Sandbox Code Playgroud)

在哪里IUser

export interface IUser {
    id: string;
    cname: string;
    sname: string;
    ...
}
Run Code Online (Sandbox Code Playgroud)

并且ISourceRedux是:

export interface ISourceRedux {
    entities: { [key: string]: ISource };
    ids: Array<string>;
    selectedIds: Array<string>;
    editingSource: ISource;
    defaultId: string;
}
Run Code Online (Sandbox Code Playgroud)

因此,我创建了以下选择器:

export const getSourcesState = (state: IStore) => state.sources;
export const getSelectedIds = (sourceRdx: ISourceRedux) => sourceRdx.selectedIds;
export const getSelectedSourceIds = createSelector(getSourcesState, fromSources.getSelectedIds);
Run Code Online (Sandbox Code Playgroud)

因此,到目前为止,为了检查是否已登录用户,我这样做了:

this.store$
  .select(fromRoot.getUserState)
  .filter(user => user.id != null && user.logged)
  .do(user => this.store$.dispatch(...))
  ...
Run Code Online (Sandbox Code Playgroud)

现在,我正在努力获取用户信息和selectedSourceIds,以便检查是否:

  1. 用户已登录(this.store$.select(fromRoot.getUserState)
  2. 然后获取所有selectedSourceIds(this.store.select(fromRoot.getSelectedSourceIds)
  3. 采取行动

我怎么能得到这个?

Deb*_*ahK 9

将该代码添加到选择器是否有意义:

// Selector functions
const getProductFeatureState = createFeatureSelector<ProductState>('products');
const getUserFeatureState = createFeatureSelector<UserState>('users');

export const getCurrentProduct = createSelector(
  getProductFeatureState,
  getUserFeatureState,
  getCurrentProductId,
  (state, user, currentProductId) => {
    if (currentProductId === 0) {
      return {
        id: 0,
        productName: '',
        productCode: 'New',
        description: 'New product from user ' + user.currentUser,
        starRating: 0
      };
    } else {
      return currentProductId ? state.products.find(p => p.id === currentProductId) : null;
    }
  }
);
Run Code Online (Sandbox Code Playgroud)

此代码在product.reducer文件中。在这里,我为产品和用户定义了功能选择器。

然后,我getCurrentProduct同时使用产品和用户功能构建选择器。

  • 这应该是公认的答案。这就是官方文档的做法:https://ngrx.io/guide/store/selectors (6认同)
  • 这还应该有效吗?我收到一条错误消息“MemoizedSelector&lt;ProductPartialState, ...”与“MemoizedSelector&lt;UserPartialState,..”不兼容 (5认同)

Jor*_*rdi 5

这是我的解决方案:

this.store$.combineLatest(
      this.store$.select(fromRoot.getUserEntity),
      this.store$.select(fromRoot.getSelectedSourceIds),
      (store, user, selectedSourceIds) => ({user: user, selectedSourceIds: selectedSourceIds}) 
    )
    .filter((proj) => proj.user.id != null && proj.user.logged)
    .do((proj) => this.store$.dispatch({type: 'DELETE_CARDS', payload: {username: proj.user.username, tokens: proj.selectedSourceIds}}))
    .take(1)
    .subscribe();
Run Code Online (Sandbox Code Playgroud)

我希望它有用。

  • 我认为这种方法没有利用重新选择(记忆选择器),如此处解释的后果 https://netbasal.com/lets-talk-about-select-and-reselect-in-ngrx-store-177a2f6045a8 (6认同)