Selectors are pure functions used for obtaining slices of store state.
Selector by route This will select based on route data, example: /invoice/123
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 --- foo.facade.ts public createInvoice (invoice: IInvoice): Observable<IStoreItem<IInvoice>> { this._store.dispatch(new CreateInvoiceAction(invoice)); return this._store.select(InvoiceSelectors.currentInvoice); } public getInvoice (): Observable<IStoreItem<IInvoice>> { // need to dispatch GetInvoiceAction ??, could pass in a string token?? return this._store.select(InvoiceSelectors.byRoute); } --- foo.selectors.ts export const byRoute = createSelector( RouterSelectors.currentParams, (params: Params): string => { return params.id; } ); export const currentInvoice = createSelector( selectFeature, (state: FeatureState) => state.counter );
IStoreItem
is just a way to wrap the response and universally (thought-out your application) check if the store slice ready.
1 2 3 4 export interface IStoreItem<T> { isLoading: boolean; item?: T; }
Using selectors with props To select a piece of state based on data that isn’t available in the store you can pass props
to the selector function.
1 2 3 4 5 6 7 8 9 10 11 12 --- foo.facade.ts public getCurrentInvoice (): Observable<IStoreItem<IInvoice>> { return this._store.pipe(select(fromRoot.getCount, { multiply: 2 })) } --- foo.selectors.ts --- here `counter` is the response from `getCounterValue` and `props` came from the call to `getCount` above. NgRx is wierd :D export const getCount = createSelector( getCounterValue, (counter, props) => counter * props.multiply );