【问题标题】:Wait for two observables to finish in order in an Angular auth guard在 Angular 身份验证守卫中等待两个可观察对象按顺序完成
【发布时间】:2018-05-10 16:32:02
【问题描述】:

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

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

}

【问题讨论】:

  • 你为什么不尝试使用 promise 它会等到你得到响应。
  • 所以实际上你想要一个接一个地运行这两个 observables。

标签: angular rxjs auth-guard


【解决方案1】:

代替zip,您可以等到第一个可观察对象用concatMap 完成,然后再运行第二个。然后第二个结果将被映射到他们两个上的&amp;&amp;操作。

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

【讨论】:

    猜你喜欢
    • 2019-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-03
    • 2017-10-12
    • 2022-08-19
    • 2019-11-30
    • 2018-05-28
    相关资源
    最近更新 更多