Angular 角度7:如果请求时间过长,则采取行动
因此,我有一个加载图标,当应用程序与服务器交互时显示。当请求发出时,将显示图标,当响应返回时,将删除图标。这相当直截了当Angular 角度7:如果请求时间过长,则采取行动,angular,request,response,Angular,Request,Response,因此,我有一个加载图标,当应用程序与服务器交互时显示。当请求发出时,将显示图标,当响应返回时,将删除图标。这相当直截了当 intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { this.spinnerService.addPendingLoad(); //We need to add this header to all outbou
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
this.spinnerService.addPendingLoad();
//We need to add this header to all outbound requests to note this is an XHR request
const authReq = req.clone({
headers: req.headers.set("X-Requested-With", "XMLHttpRequest")
});
return next.handle(authReq).pipe(
tap((event: HttpEvent<any>) => {
if(event instanceof HttpResponse) {
this.spinnerService.removePendingLoad();
}
}));
}
export class SpinnerService {
pendingLoads: number = 0;
constructor(private spinnerService: NgxSpinnerService) {}
addPendingLoad() {
this.pendingLoads++;
this.spinnerService.show();
}
removePendingLoad() {
this.pendingLoads--;
if(this.pendingLoads <= 0) {
this.spinnerService.hide();
}
}
}
intercept(req:HttpRequest,next:HttpHandler):可观察{
这个.spinnerService.addPendingLoad();
//我们需要将此标头添加到所有出站请求中,以注意这是一个XHR请求
const authReq=req.clone({
headers:req.headers.set(“X-request-With”,“XMLHttpRequest”)
});
返回next.handle(authReq).pipe(
点击((事件:HttpEvent)=>{
if(HttpResponse的事件实例){
这个.spinnerService.removePendingLoad();
}
}));
}
出口级喷丝板服务{
悬挂荷载:数量=0;
构造函数(专用spinnerService:NgxSpinnerService){}
addPendingLoad(){
这个.pendingLoads++;
这个.spinnerService.show();
}
removePendingLoad(){
这是我的心愿;
如果(this.pending)加载300毫秒。如果请求时间少于100毫秒,则无需显示图标
这种情况可能发生吗?我知道边缘情况会像一个需要105毫秒的请求一样发生,所以我仍然会遇到这种不和谐的体验,但在我看来,始终在屏幕上显示一个加载图标是一种折衷,即使它不是必需的。您可以在设置超时
校准中显示它,而不是立即显示微调器回溯:
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
let delayExpired = false;
const timeout = setTimeout(() => { // Set spinner timeout
delayExpired = true;
this.spinnerService.addPendingLoad(); // Show spinner after delay
}, 100); // Wait 100 ms to show spinner
...
return next.handle(authReq).pipe(
tap((event: HttpEvent<any>) => {
if (event instanceof HttpResponse) {
clearTimeout(timeout); // Cancel spinner timeout
if (delayExpired) {
this.spinnerService.removePendingLoad(); // Hide spinner
}
}
}));
}
}
intercept(req:HttpRequest用于演示。“addPendingLoad”可以使用当前时间戳初始化局部变量。然后将该时间戳与经过的时间进行比较。如果时间戳大于某个阈值,则显示微调器。非常感谢,我肯定是想得太多了。太简单了!