2016-11-28 70 views
1

我正在使用Angular 2的發佈版構建我的第一個應用程序(目前我在2.1.0上)。我建立了一個Route Guard,我在我的routing.ts中使用它來保護其中一個具有認證的路由。點擊後,如果未登錄,它會將用戶重定向到登錄路線。在那裏他們可以登錄,如果通過身份驗證,它會設置一個localStorage標記。這是我遇到問題的地方。然後,我想在重定向到登錄前將用戶重定向到它們最初點擊的路線,但我無法弄清楚如何在點擊Guard canActivate方法或登錄時獲取點擊路線。這似乎是一個相當常見的使用場景,但我找不到任何這樣做的例子。Angular 2安全性:登錄後重定向到點擊路線?

回答

1

好吧,這是我剝離出來例子應該說明這一點:

@Injectable() 
    export class AuthGuardService implements CanActivate 
    { 
     toUrl; 

     constructor(public authenticationService: AuthenticationService, 
        public router: Router) 
     { 
     } 

     canActivate(route, state): boolean 
     { 
      this.toUrl = state.url; //This is the url where its going 

      if (this.authenticationService.isLoggedIn()) return true; 

      this.router.navigate(['/login', {redirect: this.toUrl}]);   

     } 

} 

,並在登錄組件使用ngOnInit來檢查任何重定向ulrs:

export class LoginComponent 
{ 
    redirect; 

    constructor(
       private authenticationService: AuthenticationService, 
       private route: ActivatedRoute, 
       private router: Router) 
    { 
    } 

    ngOnInit() 
    { 
     this.redirect = this.route.snapshot.params['redirect']; 
    } 

    logIn(): void 
    { 
     this.authenticationService 
      .login(this.searchParams) 
      .subscribe(
       () => 
       { 
        this.logInSuccess(); 
       }, 
       error => 
       { 
        this.logInFail(error) 
       }) 
    } 

    logInSuccess(): void 
    { 

     if (this.redirect) 
     { 
      this.router.navigateByUrl(this.redirect); 
     } 
     else 
     { 
      this.router.navigate(['']) 
     } 
    } 

} 
+0

所以這樣的路線警衛的作品是,它擊中了警衛的canActivate方法,以確定用戶是否已經過身份驗證。在這種方法中,我試圖抓取this.router.url,但它等於用戶點擊安全路線鏈接時的路線,而不是新路線。地址欄中的URL是當前路由,而不是新的安全路由。所以我無法知道用戶點擊了哪個安全路線。或者至少我不認爲我會這樣做,我希望有人能告訴我如何獲得新的路線,以便我可以完全按照您的建議進行操作。 – Eddie

+0

我在我的應用程序中實現這一點意味着要做一段時間。我分享我是如何做到的。 –

+0

我明白你的意思了,我一直在努力尋找新路線。似乎無法在任何地方找到它。 –

相關問題