首页 > 解决方案 > 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);
      });
    }
  }
}

标签: angulartypescript

解决方案


可以激活不是(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。


推荐阅读