如何在angular2中的不同模块之间使用自定义错误处理程序服务

时间:2017-07-27 08:29:09

标签: angular

我已经创建了一个用于错误记录的模块,并且我已经扩展了默认的角度ErrorHandler类 以下是代码

@Injectable()
export class GlobalErrorHandler implements ErrorHandler {
private errorLogService: ErrorLogService;

constructor(
    errorLogService: ErrorLogService) {
    this.errorLogService = errorLogService;
}

public handleError( error: any ) : void {

    // Log to the console.
    try {
        console.error( error.message );
        console.error( error.stack );
    } catch ( handlingError ) {         
        console.error( handlingError );
    }

   }

我在我的异常处理模块中引导了这个。我想在我的其他模块中使用它 - adminmodule和clientmodule。我怎么能这样做?

1 个答案:

答案 0 :(得分:0)

你需要告诉Angular使用你的" GlobalErrorHandler"将提供程序添加到 app.module 中(因为它代表了应用程序的根级别)

这是app.module.ts

的一个例子
import { NgModule, ApplicationRef, ErrorHandler } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { GlobalErrorHandler } from './error-handler'; //<-- adapt the "from" to your file
import { ServicesModule } from './services';

import { AppComponent } from './app.component';

@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule],
  bootstrap: [AppComponent],
  providers: [
    {
      provide: ErrorHandler, 
      useClass: GlobalErrorHandler
    }
  ]
})
export class AppModule { }