繁体   English   中英

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

[英]Redirect to a specific page when using CanActivate

在我的应用程序中,当用户尝试查看“主页”页面时,他会被重定向到登录页面(如果他尚未登录)。 如果用户已经登录,或者在他登录后,我想将他重定向到“主页”页面或他在被重定向到登录之前尝试查看的任何页面。

这是我的 canActivate 模块。 我如何将用户重定向到他来自的页面,而不是返回 true? 是否可以在 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 保护链接并允许有条件地访问,例如在用户身份验证应用程序中。 链接将由 CanActivate 保护,并且只有在登录后才能访问。

所以在你的代码中你只需要删除一行

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

最终解决方案:

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

在路由文件中:

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

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