Angular 仅对带有角度HttpInterceptor的长时间请求显示微调器
我创建了一个拦截器,以便在发出HTTP请求时显示微调器:Angular 仅对带有角度HttpInterceptor的长时间请求显示微调器,angular,spinner,interceptor,Angular,Spinner,Interceptor,我创建了一个拦截器,以便在发出HTTP请求时显示微调器: import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { NgxSpinnerService } from 'ngx-spinner'; import { Observable } from 'rxjs/Ob
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()));
}
}
从'@angular/common/http'导入{HttpEvent,HttpHandler,HttpInterceptor,HttpRequest};
从“@angular/core”导入{Injectable};
从“ngx微调器”导入{NgxSpinnerService};
从“rxjs/Observable”导入{Observable};
从“rxjs/operators”导入{finalize};
@可注射()
导出类SpinnerInterceptor实现HttpInterceptor{
建造师(
专用微调器:NgxSpinnerService
) { }
拦截(req:HttpRequest)用于该目的
例如,我只想为超过1秒的HTTP请求显示微调器。我一直在尝试使用它,但我不确定如何使用它,或者它是否适合我想要的
使用拦截器有什么方法可以做到这一点吗
更新:
我在打开问题后得出了解决方案,它与@joyBlanks答案非常相似,这就是我所做的:
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();
}));
}
intercept(req:HttpRequest,next:HttpHandler):可观察{
让完成=假;
设置超时(()=>{
如果(!完成){
this.spinner.show();
}
}, 1000);
返回next.handle(req).pipe(finalize(()=>{
完成=正确;
this.spinner.hide();
}));
}
设置计时器,在1秒后显示微调器
如果请求在小于1s的时间内完成,您将永远看不到它,否则如果显示,它将被隐藏
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);
}
}));
}
定时器:NodeJS.Timeout;
截取(req:HttpRequest,next:HttpHandler):可观察{
如果(这个计时器){
clearTimeout(this.timer);
}
this.timer=setTimeout(()=>this.spinner.show(),1000);
返回next.handle(req).pipe(finalize(()=>{
this.spinner.hide();
如果(这个计时器){
clearTimeout(this.timer);
}
}));
}
正如@jonsharpe所说,你不知道哪个请求需要超过1秒的时间(可能取决于用户连接速度),除非你有一些请求需要执行大任务,比如读取大文件、执行长cpu任务等
如果您想在1秒挂起的请求后显示微调器,请继续@joyBlanks的回答,否则您将必须确定实际需要1秒以上的请求,et将为它们处理特定微调器setTimeout(()=>this.spinner.show(),1000)
这行得通吗?一开始你怎么知道一个请求是否需要一秒钟以上的时间?如果请求完成,取消超时并显式调用hide,因此如果你的请求需要不到1秒的时间,它将永远不会执行打开问题后我找到了相同的解决方案,这正是我所做的。谢谢CancelTimeou无法识别。请改用clearTimeout.lol my bad。未识别此错误。谢谢。更新回答使用此解决方案时,我得到“类型超时不可分配给类型编号”。@Dawid UseNodeJS.Timeout