-1

I have an Angular componente with two childs that requieres to share some data extracted from a http request. A service perform all the http request, and the parent component gets that data and manipulate it before it's shared to the child components.

Is it ok to perfom data manipulation (maps to modify the structure of the returned data) in the component or should I create a new service to store that logic... or place it in the existing service that performs the http request?

Thanks in advance

1 Answers1

1

What do you want to achieve?
My main goals are in the most cases readability and maintainability. Therefore my answer is written with those in mind.

If every consumer of the http request only needes the manipulated data, then the request service "owns" the logic. Still, if the manipulating logic is quite complex, it could be handled in its own service/file, but logically its part of the request service and no outsider (the components) may depend on it directly.

If some consumer need the data pure and some need it manipulated, then it gets more interesting. If for example your parent component needs the data pure and its childs need it manipulated then both ways (with an extra service and without) would be okay in my eyes. Depending on the context. ;-)
If the parent component is quite easy to understand (not to big, no complex things in it), a "mapping function" would be fine for me (as long as the component then still stays easy to understand.
If the component would get (more) complex with the mapping logic, than an extra service is a fine solution.

My Reason: Dividing code into smaller chunks is quite helpfull to tackle complexity, make it more readable, less errorprone, etc etc.
But if the chunks get too small, the file switching makes it harder to understand the code. (( Be aware i am talking of VERY small chunks ))

As a consequence i would start with adding it to the parent component, but as a pure function. That way its very easy to move it later in an extra service, because there are no interdependencies between the mapping logic and the component.
Then take a look at the result and if i do not like what i see, move it.
Also when i change things later, this "do i still like what i see" check will be done and eventually the logic will be moved then.

JanRecker
  • 1,576