0
votes

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
Use providers in the module, or providedIn in the error handler to provide the class. Not both.R. Richards
Let me clarify my question: I want to provide the service in the Core module. It looks like I have no choice, but to provide it in the Providers array of the module, because if I add CoreModule to the providedIn of my @Injectable, then I get a circular reference. Is there a different way to do it in the providedIn? I would rather do that, because of tree-shaking (see documentation link in original question). Thanks.FunkMonkey33

2 Answers

0
votes

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
votes

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