1

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?

Jo Bay
  • 96
  • 10
  • Does this answer your question? [Angular2 relative route navigate in a guard](https://stackoverflow.com/questions/40995544/angular2-relative-route-navigate-in-a-guard) – Rafi Henig Jun 25 '20 at 04:00
  • @RafiHenig Thanks I have not seen that. It is close and gave me a few ideas. But I was hopping that it could be a little more general. Because route changes from a sibling to parent at times. – Jo Bay Jun 26 '20 at 02:07

1 Answers1

3

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']);
  }

Sample app: https://github.com/usarskyy/circulardependency/blob/master/src/app/auth/feature/auth-shell/guards/can-login.guard.ts