首页 > 解决方案 > 在 canAcitvate 中调用 api - Angular

问题描述

我正在尝试与 Auth 守卫一起工作。我有一个 httpcall,它根据来自 HTTP 调用的响应设置真/假值。问题是:1)httpClients 返回一个 observable 2)httpClient 订阅需要在 Authorized 方法被调用之前发生,这样 hasSessionFlag 已经设置。

双重服务.TS

hasSession() {
    return this.http.get<{}>('API CALL', {
      withCredentials: true,
      observe: 'response'
    }).subscribe((res=>{
      if(res.status === 200) {
        this.hasSessionFlag = true;
      } else {
        this.hasSessionFlag = false
      }
    }));
  }

//Check if all the logical conditions of the user sessions pass*
  isAuthorized(): boolean {
      if (this.hasSessionFlag) {
        this.authService.login();
      } else {
        this.dualLoginRedirect();
      }
  }

  canActivate(): boolean {
    return this.isAuthorized();
  }

路由器.TS

   {
      canActivate: [DualLogonService],
      path: 'test',
      component: TestPageComponent
    }

标签: angularangular-routingangular-routerangular8angular-router-guards

解决方案


您可以轻按一下并设置 hasSessionFlag 的值,而不是订阅您的 http 调用......所以这样做..

hasSession() {
    return this.http.get<{}>('API CALL', {
      withCredentials: true,
      observe: 'response'
    }).pipe(
      tap(res=>{
      if(res.status === 200) {
        this.hasSessionFlag = true;
      } else {
        this.hasSessionFlag = false
      }
    }))
  .switchMap(res=>{
      if(this.hasSessionFlag)return this.authService.login();
      else return this.dualLoginRedirect();
}));
  }

isAuthorized(): boolean {
      if (this.hasSessionFlag) {
        this.authService.login();
      } else {
        this.dualLoginRedirect();
      }
  }

假设您的 authService.login() 和 dualLoginRedirect() 是可观察的


推荐阅读