Search code examples
angularangular-routing

Angular CanActivate guard - createUrlTree relative navigation


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.


Solution

  • 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.