加载CustomExceptionHandler时,Angular 2注入器无法找到Service

时间:2016-09-19 15:20:07

标签: angular angular2-injection

当尝试将服务注入我的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 { }

2 个答案:

答案 0 :(得分:1)

您还需要将<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.4.1</version> </dependency> 及其依赖项添加到CustomExceptionHandler

providers

答案 1 :(得分:1)

更新 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 { }