简体   繁体   中英

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

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
}

 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM