Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to select form ngrx store within an Effect using a slector with parameters

I need to build an Effect and I need a value from the store, the problem is that the selector is a selector with parameters.

following the example code:

        @Effect()
      ExampleEffect$ = this.actions$.pipe(
        ofType(
          ActionTypes.SOMETHING
        ),
        map((action: Somthing) => action.payload.myParameter),
// HERE I NEED THE PARAMETER TO PERFROM THE SELECTION
        withLatestFrom(this.store.pipe(select(selectorWithParamter(myParameter))),
        map((value) => /* do somthing with the array [myParameter, valueSelected from sotre]*/)
like image 444
ALGDB Avatar asked Nov 28 '18 12:11

ALGDB


People also ask

Can I use selector in effect NgRx?

Create Menu Selectors Similar to what you did with Actions, let's update the application to get data required by the components using NgRx Selectors. You can use Selectors by injecting NgRx's Store and calling it's select function passing in the selector's name, which returns the slice of the state that we need.


1 Answers

You can write an arrow function to pass parameters while creating a selector.

export const getAlbumById = (collectionId: number) => createSelector(getAlbumEntities, entities => entities[collectionId]);

More example

// effect

@Effect({ dispatch: true })
  upsertAlbum$ = this.actions$.pipe(
    ofType(AlbumActionTypes.UpsertAlbum),
    map((action: any) => action.payload),
    mergeMap(({ album }) =>
      this.store.pipe(
        select(selectAlbumIfExists(album.id)),
        first(),
        map(isAlbumHasName => [album, isAlbumHasName])
      )
    ),
    filter(([album, isAlbumHasName]) => !isAlbumHasName),
    map(([album]) => new LoadAlbum({ album }))
  );

// selector

export const selectAlbumIfExists = (id: string) =>
  createSelector(
    selectAlbumsEntities,
    entities => !!(entities[id] && entities[id].name)
  );
like image 191
rijin Avatar answered Sep 26 '22 13:09

rijin