angularcanactivate

Redirect to a specific page when using CanActivate


In my application when a user try to see the page "home" he is redirected to the login page (if he's not already logged in). If the user is already logged in, or after he logged in, I want to redirect him to the page "home" or whatever page he was trying to see before being redirected to login.

This is my canActivate module. Instead of returning true, how can I redirect the user to page he came from? Is it possibile to do it inside the canActivate method?

export class RouteGuardService implements CanActivate{

  constructor(private router:Router, private authService:AuthService) { }

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean | UrlTree | Observable<boolean | UrlTree> | Promise<boolean | UrlTree> {
    return this.authService.user.pipe(
      take(1),
      map(user=>{
        if(user && user.token){              
          return true;
        }
        return this.router.createUrlTree(["/login"]);
      })
    );
  }
}

Solution

  • CanActivate guards a link and allow to access conditionally such as in user authentication application. links will be guarded by CanActivate and will be accessible only after login.

    So in your code you just need to remove one line

     if(user && user.token){
          return true; //if the user is logged in you only need to return true, that's it
        }
    

    Final Solution:

      export class RouteGuardService implements CanActivate{
    
      constructor(private router:Router, private authService:AuthService) { }
    
      canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean | UrlTree | Observable<boolean | UrlTree> | Promise<boolean | UrlTree> {
        return this.authService.user.pipe(
          take(1),
          map(user=>{
            if(user && user.token){
              return true;
            }
             let url: string = state.url; // current url user trying to go to
             this.authService.setRedirectUrl(url); // store this url user is trying in authservice
             this.router.navigate(['login']);// navigate to login
             return false;
          })
        );
      }
    }
    

    in routing file:

    {
       path: 'home',
       component: HomeComp,
       canActivate: [ RouteGuardService ]
    }
    

    In AuthServiceFile once the user is succefully logged in :

     // store the URL so we can redirect after logging in
      private redirectUrl: string; 
      if (this.redirectUrl) {
        this.router.navigate([this.redirectUrl]);
        this.redirectUrl = null;
      }
    setRedirectUrl(url){
      this.redirectUrl =  url
    }