gpt4 book ai didi

angular - 等待两个 observables 在 Angular auth guard 中按顺序完成

转载 作者:行者123 更新时间:2023-12-01 23:37:51 27 4
gpt4 key购买 nike

这是我的 Angular 身份验证守卫。它检查登录状态,然后从中获取一个 ID(如果它存在)并检查分配给该 ID 的配置文件。我正在尝试使用 zip 方法解决守卫等待这两个 observable 完成的顺序,但是 checkProfileOnline 返回错误,因为 uid 未定义,因此不等待第一个 observable 完成。

@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;
});
}

}

最佳答案

代替 zip,您可以等到第一个 observable 使用 concatMap 完成,然后运行第二个。然后第二个结果将映射到对它们的 && 操作。

return checkAuthOnline()
.concatMap(res1 => checkProfileOnline()
.map(res2 => res1 && res2)
)

关于angular - 等待两个 observables 在 Angular auth guard 中按顺序完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50277500/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com