Where best to register Angular 2 providers

488 Views Asked by At

I wrote three services for an Angular 2 app, with the configuration that two are injected into the third and used there. After importing the two (all three decorated with @Injectable()), I still received an unknown provider error.

To solve it I attempted to place the injected services into the modules providers array, which worked. Is this the best approach?

Angular documentation shows listing injectables at the component level. Can I just place all injectables into the modules providers array?

Seems like this would simplify application setup as everything is configured in a central location for each module. No searching for dependencies on a component by component basis.

2

There are 2 best solutions below

0
On

Yes, put it in the @NgModule.providers if the service is to be application scoped (singleton). Only add it to the @Component.providers if the service should be component scoped1 (each component should get its own instance)


1 - See also Hierarchical Injectors

0
On

It depends upon your requirement that what kind of service you want.

Singleton service

If you want to use singleton service, you can place your service somewhere in central area. You will think you should use/place service in AppModule. But still to achieve true singleton pattern/instance you should place/declare service in CoreModule-please check how to user CoreModule and then import CoreModule to AppModule.

Multiple Instance service

If you declare serivce in @Component decorator of the components, you will have different instances of the service in different components.