Sr.Richie
Sr.Richie

Reputation: 5740

How to structure a service in AngularJS to make data available

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?

Upvotes: 0

Views: 129

Answers (2)

Nowres Rafed
Nowres Rafed

Reputation: 1138

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;
        }
    }
});

Upvotes: 2

Zdenek Hatak
Zdenek Hatak

Reputation: 1145

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.

Upvotes: 3

Related Questions