首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >AuthGuard等待接口调用

AuthGuard等待接口调用
EN

Stack Overflow用户
提问于 2021-02-01 02:49:06
回答 1查看 440关注 0票数 0

我正在尝试阻止非管理员用户访问管理仪表板本身。为此,我必须在后端检查令牌是否有效,如果有效,则确认用户实际上是管理员。我似乎能够阻止它,但我不知道如何等待在Angular 11的AuthGuard中的API调用?我必须让canActivate()方法异步吗?

AuthenticationService:

代码语言:javascript
复制
  // 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调用):

代码语言:javascript
复制
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>

包含API结果的图像

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-02-01 03:01:55

canActivate has several return values.您可以返回Observable<boolean>,只有在解析了该可观察对象之后,身份验证保护才会继续。

代码语言:javascript
复制
public canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean | Observable<boolean> {
    const token = this.commonService.getToken();

    if (token !== '' && token !== undefined) {
        return this.authenticationService.isLoggedInAndHasUserRole(token, 'Admin').pipe(
        map((hasRole) => {
            if (hasRole) {
                return true;
            } else {
                this.commonService.navigateToHome();
                return false; //
            }
        }));
    } else {
       this.commonService.navigateToLogin();
       return false;
    }
}

在您的授权服务中:

代码语言:javascript
复制
 public isLoggedInAndHasUserRole(token: string, userRole: string): Observable<boolean> {
      return this.hasUserRole(token, userRole);
  }
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65982975

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档