2

Let's say I have a component called CarDetailsComponent which makes use of a CarApiService, both of which are in CarModule. Now I want to move that component out to a SharedModule. As multiple modules also require that same component. I cannot share the whole CarModule as it already imports the other modules (e.g:, CustomerModule, ShopModule) into it.

Moving CarDetailsComponent to SharedModule is not a problem, but how do I now handle the dependent service (CarApiService) since it is also used by the component as well as other components in the CarModule.

I tried to use providers (useClass and the lot) to replace the service with another service of the module it is being used in. However, all I end up doing is copy-pasting the same functions into the services of other modules.

I did think about moving the CarApiService into the SharedModule as well, but it really belongs in CarModule (as most of the components here use it, and only CarDetailsComponent makes use of the service).

What is a better approach here?

2 Answers 2

1

Does your CarApiService need to be in a module (each module has its own singleton of that service), or does the whole app use the same instance?

If its the latter, you can remove CarpApiService from all your modules, and change your @Injctor decorator to this:

@Injectable({
  providedIn: 'root',
})

You can then import it in any constructor without having it added to that components module.

See the Angular docs for more info: https://angular.io/guide/singleton-services

Sign up to request clarification or add additional context in comments.

2 Comments

This approach works, thanks! One question: does this mean that the service class will only be imported when required (is it tree-shakeable)?
It should, depending on how you call it. check this from angular docs angular.io/guide/…
1

What about making a CarDetailModule where you declare and export the CarDetailsComponent and import it where you need it?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.