0

我正在尝试在角度 4 中使用 authgaurd 来根据尝试访问它的人的用户 ID 来限制对网站的访问。这是在 Intranet 上运行的,所有用户都将是经过 Microsoft Active Directory 身份验证的域用户。

我的应用程序正在使用 apache tomcat 的 linux 机器上运行。为了使 authguard 起作用,canActivate 方法需要首先调用 IIS Web 服务来检索当前用户的 ID。此 ID 将根据应用程序来验证用户的帐户并确定他们在系统中的角色。

我已经能够让一个订阅调用下一个订阅并且可以检索数据,但我不知道如何以这种方式实现这一点,必须将最终的布尔值传递回 canActivate 方法。下面的 canActivate 代码只是进行 Http 调用并继续前进。让它等待结果的正确方法是什么。

@Injectable()
export class OnlyKnownUsersGuard implements CanActivate {

  private isKnownUser: boolean;
  private alreadyChecked = false;

  constructor(private employeeService: EmployeeService, private httpService: HttpService) { }


  canActivate(): Observable<boolean> | Promise<boolean> | boolean {
      if ( ! this.alreadyChecked  ) {
         this.httpService.getLoggedInUser().subscribe(
                  (data: string) => this.onGetEmpInfo(data) );
          this.alreadyChecked = true;
       }
      return this.isKnownUser;
  }


  onGetEmpInfo( userId: string)  {
      this.employeeService.loadEmployeeByUserId(userId).subscribe(
          (employee: Employee) => this.isEmployeeFound(employee) ) ;
  }

  isEmployeeFound(employee: Employee)  {
      if ( employee instanceof Object ) {
          this.isKnownUser = true;
      } else {
          this.isKnownUser = false;
      }

  }

}
4

1 回答 1

0

flatMap 是答案,上面代码的语法更改为此。

@Injectable()
export class OnlyKnownUsersGuard implements CanActivate {

  private isKnownUser: boolean;
  private alreadyChecked = false;

  constructor(private employeeService: EmployeeService, private httpService: HttpService) { }


  canActivate(): Observable<boolean> | Promise<boolean> | boolean {
      if ( ! this.alreadyChecked  ) {
         this.httpService.getLoggedInUser().flatMap(
              (data: string) => this.onGetEmpInfo(data) );
      }
      else {   
          return this.isKnownUser;
      }
  }


  onGetEmpInfo( userId: string)  {
      this.employeeService.loadEmployeeByUserId(userId).map(
          (employee: Employee) => this.isEmployeeFound(employee) ) ;
  }

  isEmployeeFound(employee: Employee)  {
      if ( employee instanceof Object ) {
          this.isKnownUser = true;
      } else {
          this.isKnownUser = false;
      }
      this.alreadyChecked = true;
      return this.isKnownUser;
  }

}
于 2017-09-29T12:54:56.723 回答