Ngrx: combine two selectors

随声附和 提交于 2019-12-10 13:56:30

问题


I've built this IStore:

export interface IStore {
  user: IUser;
  sources: ISourceRedux;
}

where IUser is:

export interface IUser {
    id: string;
    cname: string;
    sname: string;
    ...
}

and ISourceRedux is:

export interface ISourceRedux {
    entities: { [key: string]: ISource };
    ids: Array<string>;
    selectedIds: Array<string>;
    editingSource: ISource;
    defaultId: string;
}

So, I've created these selectors:

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

So, up to now, in order to check if a user is logged I did that:

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

Now I'm strugling for getting user information and selectedSourceIds at the same time in order to check if:

  1. a user is logged (this.store$.select(fromRoot.getUserState)
  2. then get all selectedSourceIds (this.store.select(fromRoot.getSelectedSourceIds))
  3. dispatch an action

How could I get this?


回答1:


Would it make sense to add that code to a selector:

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

This code is in the product.reducer file. Here I define the feature selector both for the products and for the users.

I then build a getCurrentProduct selector using both the product and user feature.




回答2:


This is my solution:

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

I hope it's useful.



来源:https://stackoverflow.com/questions/43257027/ngrx-combine-two-selectors

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!