Angular 2 注入器在加载自定义异常处理程序时找不到服务



当尝试向我的CustomExceptionHandler注入服务时,Angular注入器找不到该服务。

错误:Uncaught Can't resolve all parameters for CustomExceptionHandler: (?).

设置:

CustomExceptionHandler

import { ExceptionHandler } from '@angular/core';
import { ServiceA } from '../services/a.service';
export class CustomExceptionHandler extends ExceptionHandler {
  constructor(private serviceA: ServiceA) {
    super(null, null);
  }
  call(error, stackTrace = null, reason = null) {
      //do something with the service
  }
}

app.module

@NgModule({
  declarations: [
    ...
  ],
  imports: [
    ...
  ],
  providers: [
    ServiceA,
    { provide: ExceptionHandler, useClass: CustomExceptionHandler },
  ],
  bootstrap: [AppComponent],
})
export class AppModule { }

update ExceptionHandler重命名为ErrorHandler https://stackoverflow.com/a/35239028/217408

orgiginal

添加@Injectable()到您的CustomExceptionHandler类

在app.module.ts中添加CustomExceptionHandler作为另一个提供商:

@NgModule({
  declarations: [
    ...
  ],
  imports: [
    ...
  ],
  providers: [
    ServiceA,
    CustomExceptionHandler,
    { provide: ExceptionHandler, useClass: CustomExceptionHandler },
  ],
  bootstrap: [AppComponent],
})
export class AppModule { }

您需要将CustomExceptionHandler及其依赖项添加到providers中:

@NgModule({
  declarations: [
    ...
  ],
  imports: [
    ...
  ],
  providers: [
    ServiceA,
    CustomExceptionHandler,
    { provide: ExceptionHandler, useClass: CustomExceptionHandler },
  ],
  bootstrap: [AppComponent],
})
export class AppModule { }

相关内容

  • 没有找到相关文章

最新更新