javascript - 延迟 Angular 旋转器不闪烁

标签 javascript angular typescript spinner angular-http-interceptors

目前,我正在尝试使用 Angular HttpInterceptor 显示一个微调器一次,因此每次 HttpRequest 完成时它都不会闪烁。我当前的 Interceptor.service.ts 代码如下所示:

@Injectable()
export class InterceptorService implements HttpInterceptor {
  constructor(private spinnerService: SpinnerService) {}

  showSpinner() {
    this.spinnerService.show.next(true);
    console.log('true');
  }

  hideSpinner() {
    this.spinnerService.show.next(false);
    console.log('false');
  }

  intercept(
    req: HttpRequest<any>,
    next: HttpHandler,
  ): Observable<HttpEvent<any>> {
    const responseTimer$ = next
      .handle(req)
      .pipe(filter(e => e instanceof HttpResponse));
    timer(300)
      .pipe(takeUntil(responseTimer$))
      .subscribe(() => this.showSpinner());

    return next.handle(req).pipe(
      tap(evt => {
        if (evt instanceof HttpResponse) {
          this.hideSpinner();
        }
      }),
    );
  }
}

但是如果我尝试这段代码,控制台会显示:

interceptor.service.ts:20 true
interceptor.service.ts:25 false
4 x interceptor.service.ts:20 true
4 x interceptor.service.ts:25 false
5 x interceptor.service.ts:25 false
interceptor.service.ts:25 false

但在我看来,它应该是 x 次为真,最后为假。我希望你能理解我想要实现的目标。

最佳答案

您的拦截器服务中需要一个计数器,它显示待处理请求的数量。当数字 >0 时,您会显示微调器。


编辑:

只是文本编辑器的理论

@Injectable()
export class InterceptorService implements HttpInterceptor {
  pendingCount$: BehaviorSubject<number> = new BehaviorSubject(0);

  constructor(private spinnerService: SpinnerService) {
    this.pendingCount$.pipe(
      map(Boolean),
      distinctUntilChanged(),
    ).subscribe(
      show => this.spinnerService.show.next(show),
    );
  }

  intercept(
    req: HttpRequest<any>,
    next: HttpHandler,
  ): Observable<HttpEvent<any>> {

    this.pendingCount$.next(this.pendingCount$.value++);

    return next.handle(req).pipe(
      tap(evt => this.pendingCount$.next(this.pendingCount$.value--)),
    );
  }
}

关于javascript - 延迟 Angular 旋转器不闪烁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59244649/

相关文章:

javascript - 将字符串转换为 boolean 值

javascript - 在 javascript 生成的链接中添加引用

Angular:检查 json 属性

javascript - 无法在 p-autocomplete 中将值绑定(bind)到 ngModel

Angular 5/6 : Component Interface - is it possible?

javascript - 如何让动画流畅

javascript - jQuery promise 不使用方法 html undefined

angular - 在不安装 devDependencies 的情况下为生产构建 Angular

angular - 有没有一种简单的方法来覆盖基本指令?

javascript - 模块构建失败(来自./node_modules/postcss-loader/src/index.js): SyntaxError (2:14) Unknown word