0

Studying and testing a bit AngularJS, and I have a doubt about how to structure a service to make some data available to some controllers.

I have a JSON file, and I would like to load it from my service and then use this service through my controllers to access the data.

Right now my service looks like this:

dashboardController.factory ('peopleRepository', function($http) {
return {
    getAllPeople: function() {
        return $http.get("people.json");
    }
}
});

Easy and straightforward. Then in my controller, I do something like this:

dashboardController.controller ('genderCtrl', function ($scope, $rootScope, peopleRepository) {
  $scope.males = 0;
  $scope.females = 0;

  $scope.people = peopleRepository.getAllPeople().success(function(users) {
    console.log ("SUCCESS -< ", users);
  });

});

...and of course everything it's fine and works. But I am pretty sure this is not the right approach. I would need to access this data in several controllers, and this means that basically the file will be loaded over and over, and every time I am waiting for the success event to load the content. Not really elegant. Any suggestion/hint for a newbie?

Zdenek Hatak
  • 1,135
  • 14
  • 23
Sr.Richie
  • 5,680
  • 5
  • 38
  • 62
  • you can structure your app to be SPA `single-page-app` ( which allows your to use cache the service after the first load). - however, if you've separated your application over different controllers, you'll need to inject whenever you require it. (i forgot but you can also cache services into your application) how have you structured the rest of your application? – Denis Tsoi Apr 19 '17 at 09:32

2 Answers2

3

Create a cache object to store your data in the service. The first controller saves the fetched data to it. Another one asking for the data won't call $http again, but get it from the cache object.

I guess you also going to have to use e.g. $q to create promise base function to get your data.

Also, you can use built-in cache in the $http angularjs service. See How to cache an http get service in angularjs for further info.

Community
  • 1
  • 1
Zdenek Hatak
  • 1,135
  • 14
  • 23
2

You must add, at least, a simple caching mechanism.

Here's a simple example:

dashboardController.factory ('peopleRepository', function($http, $q) {
    var people;

    return {
        getAllPeople: function() {
            if (!people) {
                // endpoint value may be put in a constant
                people = $http.get("people.json").then(function (result) {
                    return result;
                });
                // A generic error handling mechanism can also be used
            }
            return people;
        }
    }
});
Nowres Rafed
  • 1,088
  • 10
  • 14