Skip to content

Instantly share code, notes, and snippets.

@lydemann
Created October 31, 2020 09:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lydemann/e33c0234af58554d731383787a1d0f24 to your computer and use it in GitHub Desktop.
Save lydemann/e33c0234af58554d731383787a1d0f24 to your computer and use it in GitHub Desktop.
router.selectors.ts
import { ActivatedRouteSnapshot } from '@angular/router';
import * as fromRouter from '@ngrx/router-store';
import { createFeatureSelector, createSelector } from '@ngrx/store';
export interface State {
router: fromRouter.RouterReducerState;
}
export const selectRouter = createFeatureSelector<
State,
fromRouter.RouterReducerState
>('router');
export const {
selectQueryParams: selectQueryParamsNgRx,
selectQueryParam,
selectRouteData,
selectUrl
} = fromRouter.getSelectors(selectRouter);
const getRouteParams = (route: ActivatedRouteSnapshot) => {
if (route.children.length === 0) {
return route.params;
}
const combinedChildParams = route.children.reduce(
(prev, childRoute) => ({ ...prev, ...getRouteParams(childRoute) }),
{}
);
return {
...route.params,
...combinedChildParams
};
};
export const selectRouteParams = createSelector(selectRouter, routerState => {
if(!routerState?.state?.root) {
return {};
}
return getRouteParams(routerState.state.root);
});
export const selectRouteParam = (routeParam: string) => createSelector(selectRouteParams, (routeParams) => {
return routeParams[routeParam];
})
export const selectQueryParams = createSelector(
selectQueryParamsNgRx,
params => params || {}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment