简体   繁体   English

使用 CanActivate 时重定向到特定页面

[英]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.这是我的 canActivate 模块。 Instead of returning true, how can I redirect the user to page he came from?我如何将用户重定向到他来自的页面,而不是返回 true? Is it possibile to do it inside the canActivate method?是否可以在 canActivate 方法中执行此操作?

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. CanActivate 保护链接并允许有条件地访问,例如在用户身份验证应用程序中。 links will be guarded by CanActivate and will be accessible only after login.链接将由 CanActivate 保护,并且只有在登录后才能访问。

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:用户成功登录后,在 AuthServiceFile 中:

 // 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
}

 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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