When does the constructor of an injected service in angular run? When does the constructor of an injected service in angular run? typescript typescript

When does the constructor of an injected service in angular run?


The constructor of a class decorated with the Injectable decorator is called upon initialization of that class/service by the injector of a certain scope. You can't have multiple instances of the same service inside one scope, unless you force it by providing the service it via { provide: MyService, useClass: MyService, multi: true }.

The provideIn option defines the scope the service belongs to, therefore using provideIn: 'root' tells the DI to inject the service by using the RootInjector. And since a service won't get initialized multiple times in one scope, the constructor of that service is called only once, when the DI needs to inject that service into another component/service/module the first time.


It is hard to tell exactly without knowing the scope of your component and service, but I will tell you an example that should help you in this case:

In our app, we have an entire module dedicated to toggling mat-dialogs for specific bits of data, when that data is clicked on in another portion of the app.

Our app component initializes a simple service in it's constructor called dialog-toggle. Dialog Toggle is never called anywhere else. Inside the constructor of dialog-toggle, it simply listens to an observable that tells it when it should send a message to fire a different dialog.

All we had to do in order to get this service to fire its constructor was simply reference it in the constructor of our app component. Because it's in the app component, it fires every time regardless of routing or navigation, which is exactly what we needed in our case.

So long story short, I would look at when the actual component you're referencing gets initialized vs. when you're providing the service. If you've referenced it in a higher order module, chances are that the constructor has already fired.