Reputation: 804
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.
Upvotes: 12
Views: 14123
Reputation: 3796
NgRx already provides loads of selectors for you to use it. Please Refer NgRx Docs (https://v8.ngrx.io/guide/router-store/selectors)
import { getRouterSelectors, RouterReducerState } from '@ngrx/router-store';
import { createFeatureSelector } from '@ngrx/store';
export const ROUTER_FEATURE_KEY = 'router';
export const selectRouter =
createFeatureSelector<RouterReducerState>(ROUTER_FEATURE_KEY);
export const {
selectCurrentRoute, // select the current route
selectFragment, // select the current route fragment
selectQueryParams, // select the current route query params
selectQueryParam, // factory function to select a query param
selectRouteParams, // select the current route params
selectRouteParam, // factory function to select a route param
selectRouteData, // select the current route data
selectUrl, // select the current url
} = getRouterSelectors(selectRouter);
To Use it in your effects, simply do the below (taking from above code example) :
this.actions$.pipe(
...
concatLatestFrom(
this.store.select(selectQueryParams)
),
switchMap((queryParams) => { // <--- queryParams from selectors
return this.detailService
.getDetail(queryParams) // <-- use it for any logic
...
);
})
);
Upvotes: 2
Reputation: 7886
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)))
);
})
);
Upvotes: 15