这是我的 Angular 身份验证守卫。它检查登录状态,然后从中获取一个 id(如果存在)并检查分配给该 id 的配置文件。我正在尝试使用 zip 方法解决等待这两个可观察对象按顺序完成的守卫,但 checkProfileOnline 返回错误,因为 uid 未定义,因此不等待第一个可观察对象完成。
@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;
});
}
}