在 canAcitvate 中调用 api - Angular

call api in canAcitvate - Angular

我正尝试在 angular 中使用 Auth 守卫。我有一个 httpcall,它根据 HTTP 调用返回的响应设置 true/false 值。问题是:1) httpClients return 一个可观察的 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();
  }

ROUTER.TS

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

您可以点击并设置 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() 是可观察的

根据你的最新代码,我认为这就是你想要做的:

如果 API return 的状态是 200 那么你想调用 "this.authService.login();" 否则 "this.dualLoginRedirect();"

[根据您在撰写此答案时的代码 - 您的 isAuthorized() 方法不是 return 布尔值,而是 return 未定义。它必须 return 布尔值或布尔值或承诺的可观察值。我假设如果状态为 200,那么它将 return true 否则它将 return false]。有了这个假设,你只能有这样的 canActive() 方法:

canActive(): Observable<boolean> {
    return this.http.get<{}>('API CALL', {
              withCredentials: true,
              observe: 'response'
            })
            .pipe(
              map(res => {
                if(res.status === 200) {
                  //OR DO here whaterevr you want to do
                  this.authService.login();
                  //return true will render the associated component
                  //i.e. pass the guard
                  return true;
                } else {
                  this.dualLoginRedirect();
                  //return false will fail the guard.
                  return false;
                }
              })
            );
  }

您的守卫服务将自动订阅canActivate()方法的returned observable。

另外,请注意在这种方法中没有声明 class 成员。尽管如果你的警卫需要它,只需声明它们并根据你的要求使用它们。