Angular(4):自定义错误处理程序和DI:无法实例化循环依赖项

Den*_* M. 11 angular-material2 angular

我正在尝试将Angular Material 2元素注入我编写的自定义错误处理程序中,但我一直收到此错误:

Cannot instantiate cyclic dependency! ApplicationRef ("[ERROR ->]"): in NgModule AppModule in ./AppModule@-1:-1
Run Code Online (Sandbox Code Playgroud)

这是错误处理程序类:

@Injectable()
export class CustomErrorHandler implements ErrorHandler {

  constructor(private snackBar: MdSnackBar) {
  }

  handleError(error: any): void {
    //FIXME: display popup
    console.error('Error occurred!');
    console.error(error);
    this.snackBar.open('Application Error: ' + error, 'X', {
      duration: environment.snackBarTime,
    });
  }

}
Run Code Online (Sandbox Code Playgroud)

这是app.module的提供者部分

providers: [
    SearchService,
    CompanyService,
    MdSnackBar,
    PopupService,
    AuthService,
    LoginService,
    AuthGuard,
    ErrorService,
    TokenStorageService,
    BankService,
    CountryService,
    {provide: ErrorHandler, useClass: CustomErrorHandler},
    {provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true},
  ],
  exports: [
    TranslateModule
  ],
  bootstrap: [AppComponent]
})
Run Code Online (Sandbox Code Playgroud)

Den*_* M. 13

我们必须在执行handleError函数时使用服务名称手动调用注入器.

所以我不得不使用内置Inject来注入我的服务依赖.custom-error-handler调用PopupService具有MdSnackBar依赖注入的类的最终结果如下所示:

@Injectable()
export class CustomErrorHandler implements ErrorHandler {

  constructor(private injector: Injector) {
  }

  handleError(error: any): void {
    console.log(error);
    const popupService = this.injector.get(PopupService);   
  }

}
Run Code Online (Sandbox Code Playgroud)

这是PopupService:

@Injectable()
export class PopupService {

  constructor(private snackBar: MdSnackBar) {
  }

  public throwErrorPopup(textOfError: string) {
    this.snackBar.open(textOfError, 'X', {
      duration: environment.snackBarTime,
    });
  }

}
Run Code Online (Sandbox Code Playgroud)

这里提到的解决方案:https://medium.com/@amcdnl/global-error-handling-with-angular2-6b992bdfb59c