angular - 使用 Angular HTTP 拦截器管理多个同时异步服务调用的加载器/微调器
问题描述
我已经实现了 Http 拦截器并在服务启动时显示微调器,并在服务成功/失败时隐藏微调器。
代码示例:
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(req).pipe(
tap((event: HttpEvent<any>) => {
if (event instanceof HttpResponse && event.body.errCode != undefined) {
// show_spinner
}
}),
finalize(()=>{
// hide_spinner
})
}
例如,有两个服务调用同时发生;因此微调器将显示对应于两个调用,但第一个服务在2 秒内完成,第二个在5 秒内完成;现在微调器将在第一次调用完成后隐藏,将无法确认第二次服务调用。
解决方案
我想回答我自己的问题,因此可以参考上述问题/问题的解决方案。
首先,声明一个全局变量(初始化为 0)用作活动服务调用的计数器。
其次,对于每个服务拦截的增量计数(计数器变量),当服务调用完成时,减少计数(计数器变量)。
最后,如果服务计数为零,则隐藏微调器,否则显示微调器。
示例:定义一个拦截器服务来拦截 HTTP 请求。之后在拦截器服务中:
service_count = 0; // initialize the counter.
constructor(
private _route:Router
) {}
intercept(req: HttpRequest<any>, next: HttpHandler):Observable<HttpEvent<any>> {
this.service_count++; // increment the count for each intercepted http request.
// show spinner.
return next.handle(req).pipe(
finalize(() => {
this.service_count--;
// decrement when service is completed (success/failed both
handled when finalize rxjs operator used)
if (this.service_count === 0) {
// hide spinner
}
})
);
}
推荐阅读
- twilio - 一些 Twilio 页面都是表情符号和胡言乱语
- r - 如何交换单独绘制的 geom_cols 的顺序?
- batch-file - 自删除 .cmd 命令
- list - 列表
- javascript - 如何使用 mocha、chai 和 robotsjs 在命令行中测试需要用户输入的功能?
- spring - spring boot 和 mybatis 自动增加 id
- sql - 查找和删除重复地址
- javascript - 无法为 Google 表单用户创建预填网址
- c# - 即使在初始化之后,List 中的 NULL 对象也保持为 NULL
- python - 如何让我的不和谐机器人理解我的单词列表?并执行它?