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

Angular 14如何在main.ts配置全局HTTP拦截器?

Angular 14独立应用中全局HTTP拦截器配置失效的解决方法

问题原因

在Angular 14+的独立(Standalone)应用模式下,仅在bootstrapApplication的providers中注册HTTP_INTERCEPTORS无法生效——默认的HttpClient配置不会自动识别依赖注入方式注册的拦截器,需要显式启用对应支持;同时拦截器的providedIn: 'root'配置可能引发注册冲突。

解决步骤

1. 修改拦截器的注入配置

移除拦截器类上的providedIn: 'root',改为通过bootstrapApplication的providers显式注册:

import { Injectable } from '@angular/core';
import {
  HttpRequest,
  HttpHandler,
  HttpEvent,
  HttpInterceptor
} from '@angular/common/http';
import { Observable } from 'rxjs';
import { StateService } from './state.service';

@Injectable() // 移除providedIn: 'root'
export class AppInterceptor implements HttpInterceptor {

  constructor(private stateService: StateService) { console.log('AppInterceptor'); }

  intercept(req: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
    if (this.stateService.accessToken) {
      const clonedReq = req.clone({ 
        headers: req.headers.append('Authorization', 'Bearer ' + this.stateService.accessToken) 
      });
      console.log('http interceptado:', clonedReq.headers);
      return next.handle(clonedReq);
    } else {
      console.log('http no interceptado');
      return next.handle(req);
    }
  }
}

2. 调整main.ts中的HttpClient配置

在providers中添加provideHttpClient(withInterceptorsFromDi()),启用DI拦截器支持:

import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app/app.component';
import { StateService } from './app/state.service';
import { AppInterceptor } from './app/app.interceptor';
import { HTTP_INTERCEPTORS, provideHttpClient, withInterceptorsFromDi } from '@angular/common/http';
import { importProvidersFrom } from '@angular/core';
import { RouterModule, ROUTES } from '@angular/router';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

bootstrapApplication(AppComponent, {
  providers: [
    { provide: StateService, useClass: StateService },
    {
      provide: HTTP_INTERCEPTORS,
      useClass: AppInterceptor,
      multi: true
    },
    // 启用DI拦截器支持
    provideHttpClient(withInterceptorsFromDi()),
    importProvidersFrom(RouterModule.forRoot(ROUTES), BrowserAnimationsModule)
  ]
}).catch(error => console.log(error));

原理说明

  • withInterceptorsFromDi()是Angular为独立应用提供的配置项,用于启用基于依赖注入的拦截器注册机制,让框架能够识别并加载HTTP_INTERCEPTORS令牌对应的拦截器。
  • 移除providedIn: 'root'可以避免拦截器被自动注册到根注入器,确保只有显式配置的实例生效,防止重复注册导致的异常。

内容的提问来源于stack exchange,提问作者Francisco Olmo Ortiz

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 08:33:35