How to elegantly get full url from the ActivatedRouteSnapshot?
try this to get it from RouterStateSnapshot
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
console.log(state.url)
...
There's no ready to use function from Angular router to achieve that, so I wrote them:
function getResolvedUrl(route: ActivatedRouteSnapshot): string {
return route.pathFromRoot
.map(v => v.url.map(segment => segment.toString()).join('/'))
.join('/');
}
function getConfiguredUrl(route: ActivatedRouteSnapshot): string {
return '/' + route.pathFromRoot
.filter(v => v.routeConfig)
.map(v => v.routeConfig!.path)
.join('/');
}
Example output when route
is from ProjectComponent
:
const routes: Routes = [
{
path: 'project', component: ProjectListComponent, children: [
{path: ':id', component: ProjectComponent}
]
},
];
getResolvedUrl(route) => /project/id1
getConfiguredUrl(route) => /project/:id