angular - Angular 7:如果请求时间过长则采取行动
问题描述
所以我有一个加载图标,当应用程序与服务器交互时显示。当请求发出时,图标显示,当响应返回时,删除图标。这是相当直接的。
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();
}
}
}
所以我要解决的问题是,大多数时候请求会立即返回,所以最终发生的事情是你可以非常快速地显示/隐藏图标,这可能是一种不和谐的体验。
我尝试将超时设置this.spinnerService.hide();
为可能 500 毫秒,因此加载图标将始终在屏幕上显示最少的时间。这是一种更令人愉悦的体验,但最终会使加载图标显示的时间比实际更长,这会使应用程序“感觉”迟缓。
我的目标是能够以某种方式衡量请求已等待多长时间,并且仅在请求花费异常长时间时才显示加载图标。
因此,例如,大多数请求将在 100 毫秒左右响应。如果发生某些事情导致响应延迟,则触发加载图标仅在该 100 毫秒标记之后显示。因此,如果完整的请求花费了 300 毫秒,那么加载图标只会在 100 毫秒 -> 300 毫秒内显示。如果请求时间少于 100 毫秒,则不需要显示图标。
这样的事情可能吗?我确实理解边缘情况会像一个需要 105 毫秒的请求一样发生,所以我仍然会遇到那种不和谐的体验,但 IMO 是一种权衡,即使不需要,也总是在屏幕上显示一个加载图标。
解决方案
setTimeout
您可以在回调中显示它,而不是立即显示微调器:
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
}
}
}));
}
}
请参阅此 stackblitz以获取演示。
推荐阅读
- verilog - Verilog错误“连续赋值输出必须是网络”
- javascript - 引导标签输入 maxTag 在函数内不起作用
- javascript - 如何让我的复选框以 true 开头?
- python-3.x - 为什么我们使用 key=get 进行排序,key 方法是如何工作的
- java - 如何将在 EditText 控件中输入的值与 android studio 中微调器容器中的项目绑定在一起?
- version-control - 是否有类似 GitGraph 的 perforce 功能?
- javascript - 如何使用 Javascript 旋转这张卡片?
- visual-studio-code - 在 VSCode 中打开终端时的默认目录
- php - phpmyadmin: mysqli_real_connect(): (HY000/2002): 没有这样的文件或目录 - Ubuntu 20.04, phpmyadmin 4:4.9.5+dfsg1-2
- scala - 在 Scala 中使用 Flink 时,如何从类型类的 DataStreamSource 中提取值?