You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular中使用ngx-ui-loader实现连续多HTTP请求仅显示单个加载器

解决ngx-ui-loader多HTTP请求下加载器频繁启停的问题

核心思路是通过请求计数机制统一控制加载器的显示:维护一个请求计数器,仅当第一个请求发起时启动加载器,最后一个请求完成时才关闭加载器,避免单个请求触发加载器的启停。

具体实现步骤

  1. 移除NgxUiLoaderHttpModule的自动配置
    既然要自定义控制逻辑,先在app.module.ts中移除NgxUiLoaderHttpModule.forRoot(...)相关的导入和配置,避免默认的请求绑定逻辑冲突。

  2. 创建自定义HTTP拦截器
    实现一个拦截器来监听所有HTTP请求,维护请求计数并调用ngx-ui-loader的服务控制加载器:

    import { Injectable } from '@angular/core';
    import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http';
    import { Observable } from 'rxjs';
    import { finalize } from 'rxjs/operators';
    import { NgxUiLoaderService } from 'ngx-ui-loader';
    
    @Injectable()
    export class LoaderInterceptor implements HttpInterceptor {
      private requestCount = 0;
      // 排除不需要触发加载器的请求路径
      private excludeUrls = ['/assets/', '/api/health-check'];
    
      constructor(private ngxUiLoaderService: NgxUiLoaderService) {}
    
      intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
        const needLoader = !this.excludeUrls.some(url => request.url.includes(url));
        
        if (needLoader) {
          this.requestCount++;
          // 仅第一个请求时启动加载器
          if (this.requestCount === 1) {
            this.ngxUiLoaderService.start();
            // 若使用自定义loader ID,传入ID即可:this.ngxUiLoaderService.start('your-loader-id')
          }
        }
    
        return next.handle(request).pipe(
          finalize(() => {
            if (needLoader) {
              this.requestCount--;
              // 最后一个请求完成时关闭加载器
              if (this.requestCount === 0) {
                this.ngxUiLoaderService.stop();
                // 对应自定义ID:this.ngxUiLoaderService.stop('your-loader-id')
              }
            }
          })
        );
      }
    }
    
  3. 注册拦截器
    在app.module.ts的providers数组中注册自定义拦截器:

    import { HTTP_INTERCEPTORS } from '@angular/common/http';
    import { LoaderInterceptor } from './path-to-your-interceptor/loader.interceptor';
    
    @NgModule({
      // ...其他配置
      providers: [
        {
          provide: HTTP_INTERCEPTORS,
          useClass: LoaderInterceptor,
          multi: true
        }
      ]
    })
    export class AppModule { }
    

补充说明

  • 可根据项目需求修改excludeUrls数组,排除静态资源、健康检查等不需要显示加载器的请求;
  • 若项目中使用了多个不同ID的加载器,只需在start()和stop()方法中传入对应的ID即可;
  • 该逻辑确保连续发起的多个请求只会触发一次加载器的显示和隐藏,彻底解决频繁启停的问题。

内容的提问来源于stack exchange,提问作者Sachin Rana

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 15:25:27