Angular Circular Reference with Error Handler

163 views Asked by At

I am moving functionality to feature modules, and ultimately lazy loading.

Conventional wisdom indicates that app-wide singleton services should be provided in a Core module, which is loaded only once, by the Root module (see https://frontpills.com/posts/2019/core-shared-modules/ and https://github.com/gothinkster/angular-realworld-example-app/blob/master/src/app/app.module.ts).

So I have set up my error handling in Core:

import { ErrorHandler } from '@angular/core';
import { MyErrorHandler } from 'src/app/core/services/my-error-handler';

providers: [
    {
        provide: ErrorHandler,
        useClass: MyErrorHandler
    }
]

Then, in my-error-handler.ts:

import { CoreModule } from '../../core/core.module';

@Injectable({
    providedIn: CoreModule
})
export class HubErrorHandler implements ErrorHandler {
...
}

Obviously, the circular reference is CoreModule -> MyErrorHandler -> CoreModule.

But my question is: how else should I be decorating MyErrorHandler? The @Injectable({ providedIn: CoreModule}) syntax is the preferred nomenclature:

From https://angular.io/guide/providers#providedin-and-ngmodules

The example above shows the preferred way to provide a service in a module. This method is preferred because it enables tree-shaking of the service if nothing injects it.

So what is the correct way to address this situation? Should I just remove the "providedIn" from my service and add the service to CoreModule's providers array?

Thanks.

2

There are 2 answers

0
Robert Dempsey On

If app-wide, singleton services are what you're after, you can specify 'root' as your value for providedIn:

import { Injectable } from '@angular/core';

@Injectable({
    providedIn: 'root'
})
export class HubErrorHandler implements ErrorHandler {
...
}

Official documentation here

0
FunkMonkey33 On

I ended up just adding my services to the Core module's providers array.