angular - Angular 7 中的 canactivate() 中的异步等待
问题描述
我正在编写一个代码来检查浏览器是否有 userInfo。如果没有,浏览器会调用 API 从服务器获取 userInfo。仅当存在有效的 userInfo 时,才允许用户导航到页面。
我的问题是 canactivate() 不等待调用完成。我试过其他线程中提到的解析器,但它也没有用。
所以,我放了 async-await 但它也不起作用。canactivate() 在 getUser() 完成之前返回。下面的代码中 async-await 的语法是否错误?
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private router: Router, private refService: RefService, private userInfoService: UserInfoService) {
}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
this.getUser();
console.info('canActivate completed');
return this.userInfoService.getUserInfo() !== null;
}
async getUser() {
if(!this.userInfoService.getUserInfo()) {
await this.refService.getTamUser().toPromise( ).then(data => {
this.userInfoService.setUserInfo(data);
});
}
}
}
解决方案
可以激活不是(a)等待getUser。我会这样做:
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
const userInfo = this.userInfoService.getUserInfo()
if (userInfo) {
return userInfo !== null;
} else {
return this.refService.getTamUser().pipe(switchMap((data: any) => {
this.userInfoService.setUserInfo(data);
return of(data !== null);
}))
}
}
首先检查用户信息是否存在。如果没有,则从 ref 服务获取用户信息并返回一个新的 boolean 类型的 observable。false boolean 表示不允许访问或 refService 调用失败。
在此处阅读有关 switchMap的更多信息。简而言之:从原始 observable 的数据中创建一个新的 observable。
推荐阅读
- python - 如何避免熊猫将字符串转换为日期格式
- c# - 使用 C# 在字节数组中设置位
- c++ - 我应该在我的班级中有一个分配器作为成员变量吗?
- python - 为烧瓶应用程序创建 sqlite 数据库连接
- laravel - 为什么 Laravel API 路由的顺序会影响它们的工作方式
- java - 将storm升级到1.2.3时storm列表出错
- javascript - 打开文件后如何访问文件中包含的JS数组?
- c# - 如何通过代码撤销 IdentityServer 中的访问令牌
- r - 'relevel' 功能无法重置线性模型中的参考电平
- python - 如何使用 groupby('user') 制作 pandas 数据帧的时间序列图?