Created
October 31, 2020 09:43
-
-
Save lydemann/e33c0234af58554d731383787a1d0f24 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
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