【问题标题】:EmptyError: no elements in sequence when using takeWhile in angular guardEmptyError:在角度保护中使用 takeWhile 时没有序列中的元素
【发布时间】:2019-03-21 22:03:39
【问题描述】:

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

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

问题是每当 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;
      })
    );
  }
}

【问题讨论】:

    标签: typescript rxjs observable angular-cli canactivate


    【解决方案1】:

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

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

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

    }

    【讨论】:

    • 不幸的是,如果满足条件,map 不会停止轮询。换句话说,无论如何我们都会提出 3 个请求
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-18
    • 1970-01-01
    • 2018-05-16
    • 2018-10-21
    • 2023-04-02
    • 2020-05-31
    相关资源
    最近更新 更多