Ionic7+ Angular中LoadingController与HttpInterceptor加载弹窗异常问题
Ionic 7中HttpInterceptor结合LoadingController的弹窗显示/关闭异常修复方案
问题根源分析
当前代码存在两个核心问题导致弹窗异常:
- 单个
loading布尔值无法追踪并发请求数量,同时发起多个请求时,第一个请求完成就会关闭弹窗,后续请求结束时执行关闭操作会找不到目标弹窗。 tap操作会捕获所有HttpEvent(如进度事件、响应事件),导致dismissLoading被多次调用,可能在弹窗未创建完成时就执行关闭,或重复关闭引发错误。
修复后的拦截器代码
import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { LoadingController } from '@ionic/angular'; import { TranslateService } from '@ngx-translate/core'; import { Observable } from 'rxjs'; import { finalize } from 'rxjs/operators'; @Injectable({ providedIn: 'root' }) export class LoaderInterceptor implements HttpInterceptor { private activeRequests = 0; // 用计数器追踪活跃请求数量 private loadingInstance: HTMLIonLoadingElement | null = null; // 保存弹窗实例,避免重复操作 constructor( private loadingController: LoadingController, private readonly translateService: TranslateService ) {} intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { this.incrementRequestCount(); return next.handle(req).pipe( // finalize会在请求成功/失败时仅执行一次,替代tap的多次触发问题 finalize(() => { this.decrementRequestCount(); }) ); } private async incrementRequestCount() { this.activeRequests++; // 仅当第一个请求进来且无弹窗实例时,创建并显示弹窗 if (this.activeRequests === 1 && !this.loadingInstance) { this.loadingInstance = await this.loadingController.create({ message: this.translateService.instant("LOADING") }); await this.loadingInstance.present(); } } private async decrementRequestCount() { this.activeRequests--; // 所有请求完成且存在弹窗实例时,关闭并重置实例 if (this.activeRequests === 0 && this.loadingInstance) { await this.loadingInstance.dismiss(); this.loadingInstance = null; } } }
关键修改说明
- 请求计数器替代布尔值:通过
activeRequests精准追踪当前活跃请求数,确保只有第一个请求触发弹窗创建,所有请求完成后才关闭弹窗,解决并发场景下的提前关闭问题。 - 使用
finalize替代tap:finalize在Observable生命周期结束时仅执行一次,避免了tap因多个事件触发多次关闭操作的异常。 - 持有弹窗实例:直接保存创建后的弹窗实例,避免调用
loadingController.dismiss()时误操作其他弹窗,同时严格控制弹窗的创建与销毁时机。
额外优化建议
如果存在不需要显示加载弹窗的请求(如静态资源、内部接口),可以在intercept方法中添加过滤逻辑,例如:
// 跳过特定URL的请求 if (req.url.includes('/static/') || req.url.includes('/internal-api/')) { return next.handle(req); }
内容的提问来源于stack exchange,提问作者Mohamed Oussema Njimi
相关产品推荐
相关产品推荐

