navigateByUrl in canActivate

Viewed 296

I see some example code here:

https://medium.com/javascript-everyday/keep-data-in-the-state-object-during-navigation-in-angular-5657af156fb8

The specific code is:

  canActivate(next: ActivatedRouteSnapshot, { url }: RouterStateSnapshot): boolean 
  {
       if (!this.authService.isLoggedIn) {
             this.router.navigateByUrl('/auth', { state: { redirect: url } });
       }

       return this.authService.isLoggedIn;
  }

What exactly will happen here if this.authService.isLoggedIn = false?

navigateByUrl is then called in this function, before this.authService.isLoggedIn is returned, how will this behave? Will the function return "false" as value "immediately"? Or will CanActivate be "aborted" somehow by the navigateByUrl function?

A bit tricky to explain, but it seems strange to return a value from a CanActivate function that is not relevant anymore... because you have navigated away from the page that was requested...

1 Answers

It will return false, but in addition it will redirect the user.

This is useful when you try to navigate to some routes where only the logged in user should be able to navigate. So, if the user is not logged in you will probably redirect him to Login Page and return false. When you return false, then current navigation will be cancelled.

Interface that a class can implement to be a guard deciding if a route can be activated. If all guards return true, navigation continues. If any guard returns false, navigation is cancelled.

You can also return a UrlTree, and in that case the current navigation will be canceled and a new navigation will start.

If any guard returns a UrlTree, the current navigation is cancelled and a new navigation begins to the UrlTree returned from the guard.

Related