0

我们有一个 canActivate 守卫,它应该返回 Observable(boolean)。

布尔状态是从服务获得的,我们需要以 1 秒的间隔轮询 3 次,直到我们收到响应“真”。

问题是每当 takeWhile 返回 false 时,我们都会收到以下内容

error:
failure.service.ts:36 Error: Uncaught (in promise): EmptyError: no elements in sequence
EmptyError: no elements in sequence

下面是导致问题的代码。RXJS 是 ^6.2.1 版本 Angular CLI 是 ^6.0.8 版本

import { repeat, delay, takeWhile, map } from 'rxjs/operators';
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { AuthService } from '../services/auth.service';
import { Observable, of } from 'rxjs';

@Injectable()
export class AuthGuard implements CanActivate {

  constructor(private authService: AuthService) { }

  canActivate(_route: ActivatedRouteSnapshot, _state: RouterStateSnapshot): Observable<boolean> {
    return this.authService.isAuthenticated().pipe(
      delay(1000),
      repeat(3),
      takeWhile((authenticated: boolean) => {
        return !authenticated;
      })
    );
  }
}
4

1 回答 1

0

根据我的理解, EmptyError 意味着应该发出某些东西的 observable 在没有发出任何东西的情况下完成了。takeWhile 操作符,无论何时返回 false,都会导致 observable 不发射任何东西,这是 canActivate 所期望的。

我认为您需要使用地图运算符而不是 takeWhile:

canActivate(_route: ActivatedRouteSnapshot, _state: RouterStateSnapshot): Observable<boolean> {
return this.authService.isAuthenticated().pipe(
  delay(1000),
  repeat(3),
  map((authenticated: boolean) => {
    return !authenticated;
  })
);

}

于 2018-10-17T10:11:59.970 回答