首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >仅对具有Angular HttpInterceptor的长时间请求显示微调器

仅对具有Angular HttpInterceptor的长时间请求显示微调器
EN

Stack Overflow用户
提问于 2019-09-16 18:58:58
回答 2查看 2.6K关注 0票数 2

我创建了一个拦截器,以便在发出HTTP请求时显示微调器:

代码语言:javascript
复制
import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { NgxSpinnerService } from 'ngx-spinner';
import { Observable } from 'rxjs/Observable';
import { finalize } from 'rxjs/operators';

@Injectable()
export class SpinnerInterceptor implements HttpInterceptor {

  constructor(
    private spinner: NgxSpinnerService
  ) { }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    this.spinner.show();

    return next.handle(req).pipe(finalize(() => this.spinner.hide()));
  }

}

为此,我使用了ngx-spinner

例如,我只想为耗时超过1秒的HTTP请求显示微调器。我一直在尝试使用debounceTime,但我不确定如何使用它,也不知道它是否适合我想要的。

有没有办法使用拦截器做到这一点?

更新:我在打开问题后找到了解决方案,它与@joyBlanks答案非常相似,这是我所做的:

代码语言:javascript
复制
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
  let finished = false;

  setTimeout(() => {
    if (!finished) {
      this.spinner.show();
    }
  }, 1000);

  return next.handle(req).pipe(finalize(() => {
    finished = true;
    this.spinner.hide();
  }));
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-09-16 19:07:27

设置一个计时器,在1秒后显示微调。

如果请求完成<1秒,你将永远不会看到它,否则它将被隐藏,如果它被显示。

代码语言:javascript
复制
timer: NodeJS.Timeout;
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
  if(this.timer){
    clearTimeout(this.timer);
  }
  this.timer = setTimeout(() => this.spinner.show(), 1000);

  return next.handle(req).pipe(finalize(() => {
    this.spinner.hide();
    if(this.timer){
      clearTimeout(this.timer);
    }
  }));
}
票数 4
EN

Stack Overflow用户

发布于 2019-09-16 19:25:09

正如@jonsharpe所说,你不能知道哪个请求会超过1秒(可能取决于用户的连接速度),除非你有一些大任务,比如读取大文件,执行长cpu任务等。

如果你想在1秒挂起的请求后显示一个旋转器,继续使用@joyBlanks的答案,否则你将不得不确定那些实际花费超过1秒的请求来处理它们的特定旋转器

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57955402

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档