2017-04-15 56 views
0

假設我在Angular 2中有一個AuthGuard,用於檢查我是否登錄。如果我沒有登錄,我會重定向到/登錄。重定向邏輯位於AuthGuard中。有沒有在Angular路由中替換CanNotActivate的好方法?

path: '', 
component: HomeComponent, 
canActivate: [AuthGuard] 

但是如果我已經登錄,並嘗試去/登錄頁面。如果用戶已經登錄並嘗試訪問/登錄頁面,那麼重定向到主頁的最佳方式是什麼?路由器上沒有canNotActivate。我應該做兩個AuthGuards嗎?一個叫做AuthGuardNegate的東西?

有沒有很好的方法呢?

回答

1

我這樣做的方式是使用AuthGuard作爲需要驗證的頁面,並使用一個UnauthGuard作爲您希望僅在未登錄時顯示的頁面;就像你說的。 可能不是最好的方式,但該工作得很好:

import {Injectable} from '@angular/core'; 
import {CanActivate, Router} from '@angular/router'; 
import {AuthService} from '../services/auth.service'; 

@Injectable() 
export class UnauthGuard implements CanActivate { 

    constructor(private router: Router, private authService: AuthService) {} 

    canActivate() { 
     if (this.authService.isLoggedIn()) { 
      this.router.navigate(['/app']); //Path to your authenticated-only page 
     } 
     return true; 
    } 
} 

和你的路由模塊:

{ 
    path: 'login', 
    component: LoginPage, 
    canActivate: [ 
     UnauthGuard 
    ] 
}, 
相關問題