Angular 2 注入器在加载自定义异常处理程序时找不到服务
Angular 2 injector can't find Service when loading CustomExceptionHandler
尝试将服务注入我的 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 { }
您还需要将 CustomExceptionHandler
及其依赖项添加到 providers
:
@NgModule({
declarations: [
...
],
imports: [
...
],
providers: [
ServiceA,
CustomExceptionHandler,
{ provide: ExceptionHandler, useClass: CustomExceptionHandler },
],
bootstrap: [AppComponent],
})
export class AppModule { }
更新 ExceptionHandler
已重命名为 ErrorHandler
原创
将 @Injectable()
添加到您的 CustomExceptionHandler class。
将 CustomExceptionHandler 添加为 app.module.ts 中的另一个提供程序:
@NgModule({
declarations: [
...
],
imports: [
...
],
providers: [
ServiceA,
CustomExceptionHandler,
{ provide: ExceptionHandler, useClass: CustomExceptionHandler },
],
bootstrap: [AppComponent],
})
export class AppModule { }
尝试将服务注入我的 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 { }
您还需要将 CustomExceptionHandler
及其依赖项添加到 providers
:
@NgModule({
declarations: [
...
],
imports: [
...
],
providers: [
ServiceA,
CustomExceptionHandler,
{ provide: ExceptionHandler, useClass: CustomExceptionHandler },
],
bootstrap: [AppComponent],
})
export class AppModule { }
更新 ExceptionHandler
已重命名为 ErrorHandler
原创
将 @Injectable()
添加到您的 CustomExceptionHandler class。
将 CustomExceptionHandler 添加为 app.module.ts 中的另一个提供程序:
@NgModule({
declarations: [
...
],
imports: [
...
],
providers: [
ServiceA,
CustomExceptionHandler,
{ provide: ExceptionHandler, useClass: CustomExceptionHandler },
],
bootstrap: [AppComponent],
})
export class AppModule { }