Skip to content

Instantly share code, notes, and snippets.

@lydemann
Created March 16, 2021 08:52
Show Gist options
  • Save lydemann/2eb7c5a17f0897990518c30fca166b8c to your computer and use it in GitHub Desktop.
Save lydemann/2eb7c5a17f0897990518c30fca166b8c to your computer and use it in GitHub Desktop.
router.selectors.ts
const getFlattenedParentRouteParams = (route: ActivatedRouteSnapshot) => {
if (!route.parent) {
return route.params;
}
const parentRouteParams = getFlattenedParentRouteParams(route.parent);
return {
...route.params,
...parentRouteParams,
};
};
const getFlattenedChildRouteParams = (route: ActivatedRouteSnapshot) => {
if (route.children.length === 0) {
return route.params;
}
const combinedChildParams = route.children.reduce(
(prev, childRoute) => ({
...prev,
...getFlattenedChildRouteParams(childRoute),
}),
{}
);
return {
...route.params,
...combinedChildParams,
};
};
export const selectRouteParams = createSelector(selectRouter, (routerState) => {
if (!routerState?.state?.root) {
return {};
}
return {
...getFlattenedChildRouteParams(routerState.state.root),
...getFlattenedParentRouteParams(routerState.state.root),
};
});
export const selectRouteParam = (routeParam: string) =>
createSelector(selectRouteParams, (routeParams) => {
return routeParams[routeParam];
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment