我正在爲Angular 2應用程序中的路由設置AuthGuard。每條路線都有不同的用戶組,可以進入該路線。在前端,我只存儲不記名令牌,所以當調用canActivate時,我想調用API,發送我的令牌和路由,讓API解析該用戶是否有權訪問該路由,如果他們這樣做,返回true,否則返回false。在前端,我想使用該調用的結果來路由它們,或者只是將它們發送回登錄屏幕。在Angular 2中添加API調用canActivate AuthGuard
這是我正在嘗試實現這一目標:
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
this.authService.authenticateRouteForUser(state.url).subscribe(active => {
if (active) {
return true;
}
this.authService.redirectUrl = state.url;
this.router.navigate(['/login-page'])
return false;
})
}
的訂閱工作,因爲我喜歡這個測試它內部的邏輯(這基本上是正確的從角文檔通過谷歌採取的):
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean{
console.log('AuthGuard#canActivate called')
if(this.authService.isLoggedIn){
return true;
}
this.authService.redirectUrl = state.url;
this.router.navigate(['/login-page'])
return false;
}
我知道,我的第一個陳述的問題是,canActivate必須返回true或false,並且我只在訂閱中返回true或false。問題是我只想在路由驗證發生後返回true或false,這需要調用API。我接近這一切都錯了嗎?我是否應該在登錄時返回用戶角色並在前端存儲每條路由的角色,以便我可以在不打電話的情況下檢查這些角色?有沒有其他方法可以解決這個問題?