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.
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