3
votes

In the angular docs, it lists the types of feature modules that one can implement. One of those being a service module.

https://angular.io/guide/module-types

In earlier versions of Angular, you would create your service and list it in the providers array of the service NgModule. This NgModule would then be imported by the consuming application where the service will be provided in the application root injector.

Injectable()
export class MyService {}

NgModule({
    providers: [MyService]
})
export class MyServicesModule {}

NgModule({
    imports: [MyServicesModule]
})
export class AppModule {}

The newest Angular recommendation is to use the Injectable annotation, where you no longer need to list it in the providers definition.

Injectable({ providedIn: 'root'})
export class MyService {}

Therefore is there any point in creating a service module? Do you just create the services you want provided in the root injector using the above annotation and just import the service class directly and inject accoridngly?

1

1 Answers

9
votes

A service module would be required if you are using lazy loaded modules which have specific services only provided inside that module.

You can't provide a service into the same module where components of that module get the service injected.

So assume you have a MyLazyFeatureModule

@NgModule({
  imports:      [ ],
  providers:    [ ],
  declarations: [ MyFeatureComponent ],
  exports:      [ ],
})
export class MyLazyFeatureModule { }

and you have a service which contains logic only for your feature, then you cannot do the following:

Injectable({ providedIn: MyLazyFeatureModule})
export class MyFeatureService {}

You would get a cycle!

To resolve the issue you need to create a specific service module and import that module into the feature module:

@NgModule({
  imports:      [ ],
  providers:    [ ],
  declarations: [ ],
  exports:      [ ],
})
export class MyLazyFeatureServiceModule { }
Injectable({ providedIn: MyFeatureServiceModule})
export class MyFeatureService {}
@NgModule({
  imports:      [ MyLazyFeatureServiceModule ],
  providers:    [ ],
  declarations: [ MyFeatureComponent ],
  exports:      [ ],
})
export class MyLazyFeatureModule { }

Please have a look at this article (three shakable providers why, how and cycles by Manfred Steyer which explains the details of why there is a cycle quite in depth.

Besides of that use case you probably would not need a service module if you only have services provided in root. You could create one to actually have all services in one place. But maybe a core module would do for that as well. That's up to you.