user455289
user455289

Reputation: 23

Angular Dependancy Injection

I have a quick question about Angular Dependancy Injection. I have read that if you want a service to have only a single instance across your app, it should be included as a provider in the AppModule instead of any components that use it. Would this still apply other modules imported by the AppModule. For example, I want to have an AuthService as a provider in my SharedModule. If I then import this module to the AppModule, would all the components across my app share the same instance of the service?

Upvotes: 2

Views: 123

Answers (2)

Reactgular
Reactgular

Reputation: 54771

No, you can't use the NgModule imports/exports to enforce a singleton pattern. As pointed out by echonax's answer lazy loaded modules bootstrap all services again.

With that said, you can block duplicate imports on a module via the constructor. This will force the developer to manage the module load order, and also prevent a lazy module from importing it directly. If the module is imported by a secondary module it appears to get around this problem.

You can block like this in your NgModule class constructor

@NgModule({
    providers: [
        MySingletonService
    ]
})
export class ExampleModule {
    public constructor(@Optional() @SkipSelf() parentModule: ExampleModule) {
        if (parentModule) {
            throw new Error('ExampleModule is already loaded');
        }
    }
}

It's best to create modules that have just one service in them, and not use them for anything else. That makes it much easier to manage the kinds of dependencies.

Upvotes: 0

eko
eko

Reputation: 40647

Short answer: yes

but..

Do not specify app-wide singleton providers in a shared module. A lazy-loaded module that imports that shared module makes its own copy of the service.

Source: https://angular.io/guide/ngmodule#why-userservice-isnt-shared

Upvotes: 1

Related Questions