I currently have a route guard such as
export class EntityGuard implements CanActivate {
constructor(private readonly router: Router, ...) {}
canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable<boolean | UrlTree> {
...
This guard is activated for the URL
basePath/select/10/123
which means
basePath/select/:type/:id
When a certain condition is met, I need to force navigation back to
basePath/select/:type
How can I do that using createUrlTree
? E.g.
if (...) {
return of(this.router.createUrlTree([../', type]));
}
I'd need to set the
{ relativeTo: parent }
option. However I can't seem to find a way to do it.
My current solution is
private navigateBack(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
const end = state.url.indexOf(route.url[route.url.length - 1].path);
const parentUrl = state.url.slice(0, end);
return of(this.router.createUrlTree([parentUrl]));
}
Which I really don't like. String manipulation is big no for me.
The Angular CanActivate guard runs before we navigate to a route allowing us to cancel the navigation. In this tutorial, we will learn what is CanActivate guard is and how to use it to protect the route.
From the code, you see that a guard is simply a service that implements the CanActivate interface and overrides the canActivate () method. In this case, it always returns true which means access will be always granted to the user when this guard is applied to a route. CanActivateChild: used to allow or disallow access to child routes.
1. CanActivateChild is an Angular interface to guard child routes. Suppose a user has been authenticated but not authorized to visit the child routes, so child routes can be guarded using CanActivateChild. Find its declaration from the Angular doc. Method signature of canActivateChild () is the same as canActivate () .
This page will walk through Angular CanActivate and CanActivateChild route guards example. The role of Angular route guard comes into the picture when authentication and authorization is required to navigate a route.
I'm felt at the same situation, and got similar solution. The main issue is if we inject ActivateRoute
using the constructor, we get the previous route.
They are planing to pass ActivateRoute
at the canActivate
method instead of the ActivatedRouteSnapshot
.
This is the ticket: https://github.com/angular/angular/issues/22763
you can keep your solution until the angular team create better solution.
Regards.
I have a workaround to get the URL Segment for current route:
canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot,
): boolean | UrlTree | Observable<boolean | UrlTree> | Promise<boolean | UrlTree> {
const currentUrlFragments = route.pathFromRoot.flatMap((s) => s?.url ?? []).map((s) => s.path);
return this.router.createUrlTree([...currentUrlFragments, '../']);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With