Created
March 16, 2021 08:52
-
-
Save lydemann/2eb7c5a17f0897990518c30fca166b8c to your computer and use it in GitHub Desktop.
router.selectors.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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