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

Angular 6拦截器未实例化问题排查与解决

Angular 6 ErrorRequestInterceptor 未实例化问题排查与解决

最近在调试Angular 6的ErrorRequestInterceptor拦截器时踩了个坑:我在拦截器构造函数里加了console.log用来验证是否实例化,但浏览器控制台始终没输出这条日志。我已经确认拦截器的源码文件已经被执行,甚至尝试把拦截器的提供者移到模块的forRoot方法里,在AppModule中导入ErrorModule.forRoot(),但依然没效果。

问题原因

排查后发现,问题出在ErrorModule的providers配置上:拦截器的构造函数依赖ErrorCustomHandler服务,虽然我已经通过{ provide: ErrorHandler, useClass: ErrorCustomHandler }配置了全局错误处理器,但Angular的依赖注入系统没办法直接解析ErrorCustomHandler类的实例——因为它没有被显式注册到providers数组中。

解决方案

只需要在ErrorModule的providers数组里显式添加ErrorCustomHandler的注册,Angular就能正确解析依赖,拦截器也会正常实例化了。

相关代码展示

拦截器代码(带调试日志)

import { Injectable } from '@angular/core';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor, HttpResponse, HttpErrorResponse, } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/retry';
import { ErrorCustomHandler } from './error-custom-handler';

const NB_RETRIES = 5;

@Injectable()
export class ErrorRequestInterceptor implements HttpInterceptor {
  constructor(
    private errorCustomHandler: ErrorCustomHandler
  ) {
    console.log('In the constructor of error request interceptor'); // 调试用日志
  }

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(request).retry(NB_RETRIES).do((event: HttpEvent<any>) => {
    }, (error: any) => {
      if (error instanceof HttpErrorResponse) {
        this.errorCustomHandler.handleError(error);
      }
    });
  }
}

初始错误的模块注册代码

import { NgModule, ErrorHandler } from '@angular/core';
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { RouterModule } from '@angular/router';
import { CommonModule } from '@angular/common';
import { ErrorCustomHandler } from './error-custom-handler';
import { ErrorService } from './error.service';
import { ErrorRoutingModule } from './error-routing.module';
import { ErrorComponent } from './error-component/error.component';
import { ErrorRequestInterceptor } from './error-request-interceptor';

@NgModule({
  declarations: [
    ErrorComponent
  ],
  imports: [
    CommonModule,
    RouterModule,
    ErrorRoutingModule,
  ],
  providers: [
    ErrorService,
    { provide: ErrorHandler, useClass: ErrorCustomHandler },
    { provide: HTTP_INTERCEPTORS, useClass: ErrorRequestInterceptor, multi: true, }
    // 缺少 ErrorCustomHandler 的显式注册
  ]
})
export class ErrorModule { }

修改后正常的模块注册代码

@NgModule({
  // ... 其他配置保持不变
  providers: [
    ErrorService,
    { provide: ErrorHandler, useClass: ErrorCustomHandler },
    ErrorCustomHandler, // 新增:显式注册该服务
    { provide: HTTP_INTERCEPTORS, useClass: ErrorRequestInterceptor, multi: true, }
  ]
})
export class ErrorModule { }

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 08:56:23