簡體   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