Issue
I am working on the canActivate
function of a guard in Angular 9. I want to navigate in the guard relative to a path. The problem is that I need to convert ActivatedRouteSnapshot
to ActivatedRoute
.
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot){
if (allowRoute) {
return true;
} else {
this.router.navigate(['route'], { relativeTo: next });
//the error above is that relativeTo accepts a type of ActivatedRoute but next is ActivatedRouteSnapshot
return false;
}
}
What is the best way to fix this? Is there a direct way just to convert next
to ActivatedRoute
?
Solution
Angular team included createUrlTreeFromSnapshot
function in one of the latest releases (14.*), :so now you can use ActivatedRouteSnapshot
directly:
canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
if (localStorage.getItem('payed_100000_usd')) {
return true;
}
return createUrlTreeFromSnapshot(route, ['register']);
}
Answered By - Volodymyr Usarskyy
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.