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

如何在Angular项目的ngx-ui-loader中配置排除动态API请求URL

方案1:直接在模块配置阶段生成动态URL(最简单)

你的RoutingService里的baseUrl逻辑只依赖全局location.origin和常量API_URL,这两个值在AppModule初始化的时候就已经可用,不需要依赖服务实例,直接在app.module里拼接排除路径即可:

// app.module.ts
import { API_URL } from '../app.constants';

// 直接复用和RoutingService一致的逻辑生成baseUrl
function getBaseUrl(): string {
  if(location.origin === "http://localhost:4200") {
    return API_URL;
  }
  return location.origin;
}

@NgModule({
  imports: [
    // 其他模块导入省略
    NgxUiLoaderHttpModule.forRoot({
      exclude: [`${getBaseUrl()}/api/auth`],
    }),
  ]
})
export class AppModule {}

方案2:用正则匹配路径后缀(无需关心baseUrl)

如果你要排除的路径固定是/api/auth,不管前缀的baseUrl是什么,直接用正则匹配路径后缀即可,这也是官方支持的写法:

NgxUiLoaderHttpModule.forRoot({
  exclude: [/\/api\/auth$/],
});

你之前写字符串"/api/auth"不生效的原因是ngx-ui-loader默认对字符串类型的exclude规则做完整前缀匹配,你的请求是完整URL(带http前缀),自然匹配不上相对路径字符串,换成正则就可以解决。

方案3:自定义拦截器(适合baseUrl逻辑复杂的场景)

如果后续你的baseUrl获取逻辑会更复杂,必须依赖RoutingService实例,那就禁用ngx-ui-loader自带的HTTP拦截器,自己实现拦截逻辑注入服务判断:

  1. 首先移除NgxUiLoaderHttpModule的导入,只保留基础的NgxUiLoaderModule
  2. 新建自定义拦截器:
// ngx-loader.interceptor.ts
import { Injectable } from '@angular/core';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http';
import { NgxUiLoaderService } from 'ngx-ui-loader';
import { Observable } from 'rxjs';
import { finalize } from 'rxjs/operators';
import { RoutingService } from './routing.service';

@Injectable()
export class NgxLoaderInterceptor implements HttpInterceptor {
  constructor(
    private loaderService: NgxUiLoaderService,
    private routingService: RoutingService
  ) {}

  intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
    const excludePath = `${this.routingService.getBaseUrl()}/api/auth`;
    // 非排除路径才启动loader
    if (!request.url.startsWith(excludePath)) {
      this.loaderService.start();
    }
    return next.handle(request).pipe(
      finalize(() => this.loaderService.stop())
    );
  }
}
  1. 在AppModule中注册拦截器:
// app.module.ts
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { NgxLoaderInterceptor } from './ngx-loader.interceptor';

@NgModule({
  providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: NgxLoaderInterceptor,
      multi: true
    }
  ],
  imports: [
    NgxUiLoaderModule.forRoot({/* 你的全局loader配置 */}),
    // 其他模块省略
  ]
})
export class AppModule {}

内容的提问来源于stack exchange,提问作者Sanket Gupta

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 12:06:03