Angular v4: Do we store data in a Service or the Component or both? Angular v4: Do we store data in a Service or the Component or both? angular angular

Angular v4: Do we store data in a Service or the Component or both?


Generally speaking, you want to store data in a service if a lot of components use the same data. That way, it makes it extremely easy to access the same data from all different parts of your app. If one component modifies the data in the service, it will be modified for all the components that use the data which is usually very helpful. However, sometimes it is unnecessary if you only need to send data from one component to another, where one is a parent of the other. In this scenario, using input/output would be advised.

If you don't need to send the specific data between various components, then storing the data in a component is perfectly acceptable! Keep in mind that it will not be accessible from other components unless you use input/output.


Component controllers should only manage UI interactions for that specific component.

Services, in the other hand, manage interactions between components, data mapping, event handling between components that don't have a direct relation (parent > child, siblings, etc.).

The idea behind this is that a service once is created it stays in the scope and doesn't get destroyed. Components in the other hand are removed from the DOM after they are destroyed. With this said, if you use your component to do, for example, API calls to gather data, this API call will be done every time the component is initialized in the lifecycle of the framework, whereas services, as already mentioned, will persist.

The persistence of services also allow us to use things like observables, to always maintain that direct line between front-end and back-end.

Hopefully this helps.

EDIT

Keep in mind that the Angular.io tutorial is separated into multiple sections to help give a complete introduction to the framework as the user follows the tutorial.


If multiple Components share data, put it in a service... when possible. I say when possible, because by making the service manage the data, you now have to worry about stale data. My goto data-storage location is in the Component, but you have to be careful doing this, as you don't want to cause the site to have to re-fetch data all the time.

Personally, most of my components manage their own data, in order to avoid stale-data issues.

If you are not worried about this, you could even use a caching service, that will, instead of storing the data in ram, store it in localstorage, or session storage, to make sure the site doesn't get slowed down by loads of data being put in the computers Ram.

I am by no authority an expert on this though, this is just my opinion.