Search code examples
angularmoduleangular2-services

Angular 2 import service from other feature module


Context

Say I have a Angular 2 feature module Movies and a feature module Dashboard. The Movie module has a service movies.service which is exposed/provided by the Movies module.

Now a component in the Dashboard module also wants to use this service to display a subset of movies.

Question

Should you just import the service in that component and use the service, effectively making the Dashboard module dependent on the Movies module, or should you move the service to a Shared module and import this in both feature modules?

A feature module depending on another feature module feels a bit weird to me, but if you import the service via the Shared module in each feature module, won't the service be instantiated twice, one for each import?

Well then you could add it to the core module to make sure it is only imported once.. but it is not a core service so that feels even weirder!

Arg, I feel like I am creating a problem that isn't there.. Could somebody unwind my brain please.. thx :P


Solution

  • I would put the movie.service into the movie.module. If that module is not lazy loaded, then the injectable service is available for other modules. With lazy loading things gets complicated, because a new injection context is created then.

    But if you decide to put your service into the sharedModule it should also work, but it's dangerous. You won't have two instances of your service in one time, because the root injector will always take the last initializied one, except there is a lazy loaded module importing this Shared-Module.

    The angular stlye guide tells, to put singleton service whose instance wil be shared throughout the application in the CoreModule.

    for further informations read the angular style guide: https://angular.io/styleguide#!#04-11