【发布时间】:2017-09-29 20:54:56
【问题描述】:
我正在尝试在 Angular 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;
}
}
}
【问题讨论】:
-
如果你想让它等待,你需要返回一个可观察的(或承诺),正如签名所暗示的那样。尝试链接
.map将 API 响应转换为您需要的布尔值。 -
我试过了,但我得到了一个语法错误。我认为确切的错误是 Observable
> 不是 Observable 。我想不出正确的语法。 -
听起来您需要
flatMap才能将O<O<b>>展开为O<b>,但没有minimal reproducible example 我只能这么说。
标签: angular observable auth-guard