angularjsangular-servicesangular-controller

Angular 1.x : Specific Scenario When To Use Controller / Service


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 ?


Solution

  • You have following options:

    1. 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.
    2. Call the data once, and store it in a service. Afterwards, inject the service everywhere you need the data.
    3. 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.