Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to share functions between components in angular?

Tags:

angular

I have 3 type of components to handle forms. They are:

  • EntityFormEditComponent //To Edit
  • EntityFormViewComponent // To Visualize
  • EntityFormCreateComponent // To Create

They have a common parent that is the EntityFormComponent that share the basic logic between themself.

When i create a new entity, this entity extends from the base forms components, like this:

  • UserFormEditComponent extends from EntityFormEditComponent
  • UserFormViewComponent extends from EntityFormViewComponent
  • UserFormCreateComponent extends from EntityFormCreateComponent

This way of organizing my project create a problem that is:

How i can share the common methods between these 3 components ?

I think that service would be a solution, but is not recomendable because they aren't used to handle component logic.

like image 749
Carlinhos Avatar asked May 29 '18 17:05

Carlinhos


1 Answers

I think that service would be a solution, but is not recommendable because they aren't used to handle component logic.?

Angular distinguishes components from services in order to increase modularity and reusability. and It's Good Practice to Delegate complex component logic to services

From Angular Style Guide
Do limit logic in a component to only that required for the view. All other logic should be delegated to services.

Do move reusable logic to services and keep components simple and focused on their intended purpose.

Why? Logic may be reused by multiple components when placed within a service and exposed via a function.

Why? Logic in a service can more easily be isolated in a unit test, while the calling logic in the component can be easily mocked.

Why? Removes dependencies and hides implementation details from the component.

Why? Keeps the component slim, trim, and focused.

Usage of Services In Angular also ensures that you are not violating DRY and SRP principles of software development,For your scenario the best solution is to use a service

Bonus: what, why and when to use services?

like image 142
2 revs Avatar answered Nov 13 '22 17:11

2 revs