Angular 在一个角度验证保护中,按顺序等待两个观测值完成
这是我的有棱角的授权守卫。它检查登录状态,然后从中获取id(如果存在),并检查分配给该id的配置文件。 我试图用zip方法解析等待这两个可观察对象完成的保护,但是checkProfileOnline返回了一个错误,因为uid未定义,因此没有等待第一个可观察对象完成Angular 在一个角度验证保护中,按顺序等待两个观测值完成,angular,rxjs,auth-guard,Angular,Rxjs,Auth Guard,这是我的有棱角的授权守卫。它检查登录状态,然后从中获取id(如果存在),并检查分配给该id的配置文件。 我试图用zip方法解析等待这两个可观察对象完成的保护,但是checkProfileOnline返回了一个错误,因为uid未定义,因此没有等待第一个可观察对象完成 @Injectable() export class AuthGuard implements CanActivate { constructor( private authService: AuthService,
@Injectable()
export class AuthGuard implements CanActivate {
constructor(
private authService: AuthService,
private userService: UserService,
private router: Router
) {}
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
let obsArray: Observable<boolean>[] = [];
obsArray.push(this.checkAuthOnline(), this.checkProfileOnline());
// CHECK FOR AUTH AND PROFILE ONLINE
return Observable.zip(obsArray).map(res => {
if (res[0] && res[1]) {
return true;
}
return false;
});
}
checkProfileOnline(): Observable<boolean> {
return this.userService.userCheck(this.authService.uid).map(profile => {
if (profile) {
this.userService.user = profile;
return true;
}
this.router.navigate(['/']);
return false;
});
}
checkAuthOnline(): Observable<boolean> {
return this.authService.authStatus().map(loggedIn => {
if (loggedIn) {
this.authService.uid = loggedIn.uid;
return true;
}
return false;
});
}
}
@Injectable()
导出类AuthGuard实现了CanActivate{
建造师(
私有authService:authService,
私有用户服务:用户服务,
专用路由器
) {}
激活(
下一步:ActivatedRouteSnapshot,
状态:RouterStateSnashot):可观察的|承诺|布尔值{
let obsArray:Observable[]=[];
obsArray.push(this.checkAuthOnline()、this.checkProfileOnline());
//联机检查身份验证和配置文件
返回Observable.zip(obsArray.map)(res=>{
if(res[0]&&res[1]){
返回true;
}
返回false;
});
}
checkProfileOnline():可观察{
返回this.userService.userCheck(this.authService.uid).map(profile=>{
如果(配置文件){
this.userService.user=profile;
返回true;
}
this.router.navigate(['/']);
返回false;
});
}
checkAuthOnline():可观察{
返回此.authService.authStatus().map(loggedIn=>{
if(loggedIn){
this.authService.uid=loggedIn.uid;
返回true;
}
返回false;
});
}
}
您可以使用concatMap
等待第一个可观察对象完成,然后在上运行第二个。然后,第二个结果将映射到它们两个上的&
操作
return checkAuthOnline()
.concatMap(res1 => checkProfileOnline()
.map(res2 => res1 && res2)
)
为什么不尝试使用一个承诺,它会一直等到你得到响应,所以实际上你想要一个接一个地运行这两个可观察对象。