Injecting services in custom ErrorHandler causes “Cannot instantiate cyclic dependency!” error, how can I fix this?

后端 未结 2 1069
暗喜
暗喜 2021-01-01 16:28

I have the following code :

app.module.ts:

NgModule({
    declarations: [
        AppComponent
    ],
    im         


        
相关标签:
2条回答
  • 2021-01-01 16:48

    The ErrorHandler is created before the providers. So we need Injector for dependency injection in our custom error handler class.

    @Injectable()
    export class MyErrorHandler implements ErrorHandler{
       constructor(private injector: Injector) { } 
      handleError(error: any) {
          let router = this.injector.get(ServiceName);
    
        }
    }
    

    Create a default service via Angular cli and check the first part see providedIn: 'root',

    @Injectable({
      providedIn: 'root',
    })
    export class CustomService{
      constructor(private otherService: OtherService) { // ok not failed } 
    }
    

    For more detail check angular @Injectable-level configuration

    @NgModule-level injectors You can configure a provider at the module level using the providers metadata option for a non-root NgModule, in order to limit the scope of the provider to that module. This is the equivalent of specifying the non-root module in the @Injectable() metadata, except that the service provided via providers is not tree-shakable.

    0 讨论(0)
  • 2021-01-01 16:58

    You can use this workaround to break up cyclic dependencies with DI

    @Injectable()
    export class MyErrorHandler implements ErrorHandler {
      private _appLog: AppLog;
      constructor (injector:Injector) {
        setTimeout(() => this._appLog = injector.get(AppLog));
      }
      ...
    }
    

    Angulars DI itself just doesn't support cyclic dependencies.

    0 讨论(0)
提交回复
热议问题