ngrx: how to pass parameters to selector inside createSelector method

a 夏天 提交于 2019-12-04 03:28:57

From this blog post: https://blog.angularindepth.com/ngrx-parameterized-selector-e3f610529f8

As of NgRx 6.1 selectors also accepts an extra props argument. Which means you can now define a selector as the following:

export const getCount = createSelector(
  getCounterValue, 
  (counter, props) => counter * props.multiply
);

this.counter = this.store.pipe(
  select(fromRoot.getCount, { multiply: 2 })
);

Ah ... but rereading your question, you are asking then how to build another selector that uses this selector? The above-linked article suggests building a factory function.

I am using "@ngrx/entity": "7.2.0", and I can see that props are passed to each selector, for example in my component I am calling:

this.isActive$ = this.store.pipe(select(fromClient.isActive, { id: 'someid' }));

And then in my reducer I have the following:

export const getClientState = createFeatureSelector<ClientState>('client');

export const getClient = createSelector(
  getClientState,
  (state, props) => {
    // do something with props.id to get the client then:
    return state;
  }
);

export const isActive: = createSelector(
  getClient, // props are passed to here
  (state: any) => { // i don't add the props argument here, as i don't need them
    return state.isActive;
  }
);

With fixed parameters for the selector it works fine:

this.counter = this.store.pipe(
    select(fromRoot.getCount, { multiply: 2 })
);

but what's about dynamic parameters:

this.counter = this.store.pipe(
   select(fromRoot.getCount, { multiply: this.getMultiplier() })
);

getMultiplier() {
    ...
    return myUser.multiplier + magicFactor;
}

that did not work in my app :-( (NgRx version 8)

You could use the projector function:

export interface Record {
  // Some sort of record interface
}

export interface State {
  records: Record[];
}

export const getRecords = createSelector(
  getState,
  (state: State): Record[] => state.records)
);

export const getRecordByIndex = createSelector(
  getRecords,
  (records: Record[], { index }) => records[index]),
);

export const getFirstRecord = createSelector(
  getRecords,
  (records: Record[]) => getRecordByIndex.projector(records, { index: 0 })
);
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!