Angular 2 injector can't find Service when loading CustomExceptionHandler

谁说我不能喝 提交于 2019-12-11 07:56:08

问题


When trying to inject a service into my CustomExceptionHandler, the Angular injector cannot find the service.

The error: Uncaught Can't resolve all parameters for CustomExceptionHandler: (?).

The setup:

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

回答1:


update ExceptionHandler was renamed to ErrorHandler https://stackoverflow.com/a/35239028/217408

orgiginal

Add @Injectable() to your CustomExceptionHandler class.

Add CustomExceptionHandler as another one of your providers in the app.module.ts:

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



回答2:


You need to add CustomExceptionHandler and its dependencies to providers as well:

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


来源:https://stackoverflow.com/questions/39576701/angular-2-injector-cant-find-service-when-loading-customexceptionhandler

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!