Let's say, In a web app, a particular JSON is frequently used across multiple pages, for e.g:
{
"employees":[
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter", "lastName":"Jones"}
]
}
So getting a firstName()
or lastName()
for all employees should be considered as a part of the controller or the Service?
I could only think of using services as it is frequently used across app and controller be getting this data and it will be thinner too.
Is this right approach ?
You have following options:
- Make a REST/HTTP call every time you need this data in a certain controller. Therefore, create a EmployeesService which calls the HTTP endpoint to get the data.
- Call the data once, and store it in a service. Afterwards, inject the service everywhere you need the data.
- Fetch the data from the HTTP endpoint when your app starts, and store it in the local storage of the browser or inside the $rootScope, so you can access it from everywhere.
In the end, it depends on:
So yes, with a service, you are on a safe side. Afterwards, inject it into the controller and use it from there. How and how often the data gets into the service: Your decision.