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.
NgRx is an implementation of Flux Pattern for angular leveraging RxJs. Inspired by Redux it uses a centralized state store approach.
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.
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.
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)))
);
})
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With