我有一个auth.service和data.service.auth.service从data.service获取数据,但它在数据到达之前进行检查。因此它返回undefined。
auth.service获取这样的数据;
get isLoggedIn(): boolean {
const user = JSON.parse(localStorage.getItem('user'));
const emailVerify = this.dataservice.userStatService(user.uid);
console.warn(emailVerify)
return (user !== null && emailVerify !== false && emailVerify !== undefined ) ? true : false;
}
像这样的data.service检查用户状态功能;
userStatService(uid: any): any{
console.error(uid)
this.get(uid)
.subscribe(
data => {
console.warn('status set', data.status)
this.statData = data.status;
},
error => {
console.log(error);
});
return this.statData;
}
这个代码现在是这样工作的;参见控制台日志
我正在等待您的代码示例,谢谢。
更新:auth.guard代码;
canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
if (this.authService.isLoggedIn() !== true) {
this.router.navigate(['/auth/login'], { queryParams: { returnUrl: 'dashboard' } })
.then(() => {
this.authService.SignOut();
});
}else{
return true;
}
}
可观察对象异步执行,您需要返回可观察对象并在消费者中订阅才能正确使用它:
// return observable
userStatService(uid: any): any{
console.error(uid)
return this.get(uid)
}
isLoggedIn() {
const user = JSON.parse(localStorage.getItem('user'));
this.dataservice.userStatService(user.uid).subscribe(emailVerify => {
console.warn(emailVerify)
})
// really can't do this while working with async execution. doesn't work.
//return (user !== null && emailVerify !== false && emailVerify !== undefined ) ? true : false;
}
如果这是一个警卫,使用map操作符并返回整个可观察的,angular期望布尔值或可观察的:
isLoggedIn(): Observable<boolean> {
const user = JSON.parse(localStorage.getItem('user'));
if (!user)
return of(false); // null guard and slight performance improvement
return this.dataservice.userStatService(user.uid).pipe(map(emailVerify => {
console.warn(emailVerify)
return (emailVerify !== false && emailVerify !== undefined ) ? true : false;
}))
}
在你的护卫下,你需要再次返回可观察到的:
canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
return this.authService.isLoggedIn().pipe(
map(isLoggedIn => {
if (!isLoggedIn) {
this.router.navigate(['/auth/login'], { queryParams: { returnUrl: 'dashboard' } }).then(() => {
this.authService.SignOut();
});
}
return isLoggedIn;
})
)
}
angular guard将处理订阅,但必须将observable返回给guard。