Should I use an Angular Component as an Injectable Service?

Viewed 136

Which is the best practice to use in Angular when I need some method for a component that it is hosted on another component? Should I use the component who has the method as a service itself, specifying it on the providers specifications of the module or create a dedicated .service.ts file to this operation and inject it on the modules declaration?

3 Answers

This question has been flagged by at least one user as "opinion" based, but I disagree.

Angular has the specific roles of "Component" and "Service" and your 'shared method' clearly (to me) is in the category of a Service.

The reason that this tends to become unclear is because many developers tend to put service-like logic directly into components. That's probably because it's easy to do, and because a lot of simplistic examples available on the web reinforce it.

However, if you take the view the a Component is actually a "Controller" in MVC terms, then you will see that logic in a Component that manipulates data does not belong there.

So, short answer....extract the method to a Service.

If you must use a unique method on two different components, the common path is abstracting that method in a shared.service.ts or something like that and then inject it trough dependency injection on both components .ts

If in the same module:

You can just use <app-user-list></app-user-list> to use a component in an other one.

In a different module:

If you're looking to reuse some of your components or services indifferent part of your application, you should use what's called a shared module. You can then import that module in any module of your choice to get access to it's components or services.

Here's a list of things you could find in a shared module:

  • navigation component
  • confirmation dialog component
  • order-list component
  • notification service
Related