Sammy
Sammy

Reputation: 3687

Angular 2 Service Module vs. Service Class within Feature Module

Is it recommended to set up an entire module that contains all the app service classes in Angular 2, or would it be better to create a service class within each feature module?

In the latter case, can those services be shared across the whole app if they're declared as a Provider within that feature module?

Upvotes: 2

Views: 449

Answers (2)

birwin
birwin

Reputation: 2684

My opinion... I have found placing services in a shared module is simpler unless the service is used primarily by one feature module.

The advantages are reduced coupling between feature modules and its just easier to locate the services when they are all in one general location.

Services in a feature module can be shared across the whole app. Just include them in the "Providers" section of your feature module and import the feature module in your app.module

Upvotes: 0

John Siu
John Siu

Reputation: 5092

Is it recommended to set up an entire module that contains all the app service classes in Angular 2, or would it be better to create a service class within each feature module?

This seems to be a practice/style question. No definitive answer.

IMHO, if there is group of services always use together, packing them into feature module make sense. One service class per module seems over kill.

In the latter case, can those services be shared across the whole app if they're declared as a Provider within that feature module?

Yes, remember to export them inside the feature module's module.ts.

Upvotes: 1

Related Questions