我正在尝试阻止非管理员用户访问管理仪表板本身。为此,如果令牌有效,我必须检查后端,如果有效,则用户实际上是管理员。我似乎能够阻止它,但我不知道如何在 Angular 11 的 AuthGuard 中等待 API 调用?我必须使 canActivate() 方法异步还是什么?
身份验证服务:
// This method works and returns an Observable<boolean>
public hasUserRole(theAccessToken: string, userRole: string): Observable<any> {
const httpOptions = {
headers: new HttpHeaders({
accessToken: theAccessToken,
requiredUserRole: userRole,
})
};
return this.http.get<any>(Constants.API_ENDPOINT_GET_USER_ROLES, httpOptions);
}
// This method, I don't know how to implement... I tried .pipe and .tap and whatnot but I can't get anything to wait for the API call to finish.
public isLoggedInAndHasUserRole(token: string, userRole: string): boolean {
// return this.hasUserRole(token, userRole); // TODO: How to wait for this API call? .map doesn't seem to work in Angular11 and I can't get the .pipe() to work either.
}
Auth Guard(有效,但我不知道如何等待 API 调用):
public canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
const token = this.commonService.getToken();
if (token !== '' && token !== undefined) {
if (this.authenticationService.isLoggedInAndHasUserRole(token, 'Admin')) {
<snip for brevity>