1

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

错误:Uncaught Can't resolve all parameters for 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
  }
}

应用程序模块

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

2 回答 2

1

您还需要添加CustomExceptionHandler及其依赖项providers

@NgModule({
  declarations: [
    ...
  ],
  imports: [
    ...
  ],
  providers: [
    ServiceA,
    CustomExceptionHandler,
    { provide: ExceptionHandler, useClass: CustomExceptionHandler },
  ],
  bootstrap: [AppComponent],
})
export class AppModule { }
于 2016-09-19T15:21:44.960 回答
1

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

原版

添加@Injectable()到您的 CustomExceptionHandler 类。

在 app.module.ts 中添加 CustomExceptionHandler 作为您的另一个提供程序:

@NgModule({
  declarations: [
    ...
  ],
  imports: [
    ...
  ],
  providers: [
    ServiceA,
    CustomExceptionHandler,
    { provide: ExceptionHandler, useClass: CustomExceptionHandler },
  ],
  bootstrap: [AppComponent],
})
export class AppModule { }
于 2016-09-19T15:27:03.007 回答