我的身份验证服务具有这些行为主题
public isLoggedIn$: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
public isLoaded$: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
当用户已经登录到站点时,需要一秒钟的时间来加载身份验证服务并将isLoggedIn $设置为true。有没有办法在返回之前等待行为的下一个值更改?我想它看起来像这样
export class AuthGuard implements CanActivate {
private authLoaded = false;
private loggedIn = false;
constructor(
private authService: AuthService,
private router: Router,
private toast: ToastrService,
) {
authService.isLoggedIn$.subscribe(loggedIn => {
this.loggedIn = loggedIn;
});
authService.isLoaded$.subscribe(authLoaded => {
this.authLoaded = authLoaded;
});
}
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot,
): Observable<boolean> | boolean {
if (this.authLoaded === false) {
this.authService.isLoggedIn$.subscribe..awaitForNextValue..(loggedIn => {
this.loggedIn = loggedIn;
return of(this.loggedIn);
});
} else {
return this.loggedIn;
}
}
}
答案 0 :(得分:1)
在CanActivate文档中,检查返回类型。如果您返回一个布尔值而不是其他布尔值(Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree
),它将布尔同步执行,而不是异步执行。
此外,警卫将按照它们在该路由的警卫数组中的顺序执行。