2017-03-16 108 views
0

我一直在尋找這最後4個小時,並找不到任何答案。角2路由器canActivate身份驗證警衛

我有幾個Authguards寫的,我想告訴路由器,如果其中一些是真的,它應該給予許可,但角2路由器檢查每個守衛是否爲真,然後給予許可,否則它會阻止鏈接,有沒有這樣做的好方法?我可以寫幾個認證衛士,但我認爲這不是一個好主意。

例如我想/profile頁是由管理員和超級用戶訪問,但我不希望普通用戶訪問/profile

+0

你可以使用guard來做這個例子,例如檢查即將到來的用戶是admin,SU然後返回true,否則返回true,否則你可以邏輯處理它 –

回答

1

你可以注入你的警衛在一個父衛隊,並採取控制自己:

@Injectable() 
    class Guard implements CanActivate { 

     constructor(private guard1: Guard1, private guard2: Guard2) {} 

     canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot):boolean { 
     // I'm assuming that your guard1.canActivate and guard2.canActivate return boolean 
     return guard1.canActivate() || guard2.canActivate(); 
     } 
    } 

在你的路線配置只使用Guard後衛:

{ 
    path : 'route', 
    canActivate : Guard 
    ... 
} 

,當然你可以在其他路線中使用guard1guard2

1

您可以在身份驗證警衛中使用CanLoad接口。例如,讓我們說你的路線就是這樣的;

{ 
    path: 'profile', 
    component: 'ProfileComponent', 
    canLoad: [ 
      AuthenticationGuard 
    ] 
} 

在你AuthenticationGuard,實現CanLoad接口。如果用戶沒有此鏈接的權限,則不會加載此路由的模塊。

export class AuthenticationGuard implements CanLoad { 
    canLoad(route: Route): Observable<boolean> | Promise<boolean> | boolean { 
      //in here ask your authentication service to check current user has permission for this route 
    } 
} 

我希望它可以幫助,請讓我知道進一步的問題。