簡體   English   中英

我可以在Angular組件上獲取canActivate返回值嗎?

[英]Can I get canActivate return value on Angular component?

我使用AuthGuard保護我的某些組件,而有些則不是。 即,盡管用戶尚未登錄,但仍可以訪問它。

在該組件上,我想顯示已登錄用戶和未登錄用戶之間的UI差異。 例如,已登錄的用戶將在邊欄中顯示“注銷”菜單,而未登錄的用戶將顯示在“登錄”菜單中。 因此,我需要在我的組件上獲取canActivate值(或用戶是否已登錄的狀態)。

這是我的AuthGuard文件:

@Injectable({ providedIn: 'root' })
export class AuthGuard implements CanActivate {
    constructor(
        private router: Router,
        private authenticationService: AuthenticationService
    ) { }

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    const currentUser = this.authenticationService.currentUserValue;
    if (currentUser) {
        // check if route is restricted by role
        if (route.data.roles && route.data.roles.indexOf(currentUser.role) === -1) {
            // role not authorised so redirect to home page
            this.router.navigate(['/']);
            return false;
        }

        // authorised so return true
        return true;
    }

    // not logged in so redirect to login page with the return url
    this.router.navigate(['/login'], { queryParams: { returnUrl: state.url } });
    return false;
   }
}

我正在搜索並詢問一些消息來源,他們說這無法完成。 但是,也許您可​​以說出另一種方法

解決方案之一是使用定義用戶是否通過身份驗證的方法創建服務,並在AuthGuard和任何組件中使用此方法

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM