我正在尝试在角度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;
}
}
}
答案 0 :(得分: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;
}
}