Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get route params inside ngrx effects using ngrx-router-store?

I am having effect class where I want to load details based on router params ID

@Effect()
  getDetails$ = this.actions$.ofType(DetailActions.GET_DETAILS).pipe(
    map(toPayload),
    switchMap(payload => {
      return this.detailService
        .getDetail(payload)//I want router params here in payload
        .pipe(
          map(detail=> new DetailActions.GetDetailSuccess(detail)),
          catchError(error =>
            Observable.of(new DetailActions.GetDetailFail(error))
          )
        );
    })
  );

I want to get router params in payload, so that I don't have to pass payload from component but directly get it from effects class.

like image 929
Borad Akash Avatar asked Jan 11 '18 05:01

Borad Akash


People also ask

What is NgRx router store?

NgRx is an implementation of Flux Pattern for angular leveraging RxJs. Inspired by Redux it uses a centralized state store approach.

What is a good use case for NgRx store?

NgRx is a global state management library that helps decouple the Domain and Business layers from the Rendering layer. It's fully reactive. All changes can be listened to using simple Observables, which makes complex business scenarios easier to handle.

How do I write an effect in NgRx?

Getting started. It will add and install the @ngrx/effects library to your package. json and scaffold your AppModule to import the NgRx EffectsModule into your application. With the setup complete, we can start modifying the app to introduce and handle some API calls using Effects.


1 Answers

If you already have a selector mapping to your app router state:

export const getRouterState = createFeatureSelector<
  fromRouter.RouterReducerState<RouterStateUrl>
>('router');

Then you can use withLatestFrom from rxjs/operators to get your params from the router state and maybe merge them with your action's payload, something like what follows:

@Effect()
getDetails$ = this.actions$.pipe(
    ofType(DetailActions.GET_DETAILS),
    withLatestFrom(
        this.store.select(fromRoot.getRouterState),
        (action, router) => {
            // do your logic here
            // and return a newPayload:
            return {
                id: router.state.params.id,
                payload: action.payload
            }
        }
    ),
    switchMap(newPayload => {
        return this.detailService
        .getDetail(newPayload)
        .pipe(
            map(detail=> new DetailActions.GetDetailSuccess(detail)),
            catchError(error => Observable.of(new DetailActions.GetDetailFail(error)))
        );
    })
);
like image 66
Salem Ouerdani Avatar answered Sep 27 '22 18:09

Salem Ouerdani