Search code examples
angularjsangular-servicesangular-factory

Limit http calls from a factory service


I'm using a factory service to fetch some data using the $http service. The problem here, I dont want to make a http request each time, I want to save this data somewhere and get a local copy of it when needed. To that end I thought creating an array inside that factory and assign the loaded data to it on the first call, and then just return it when required, instead of loading it again from the server. In my case, it the http service is fired every time. How can I fix this? I read here but that does not answer my question.

This is my factory:

angular.module("app").factory("getDataService", ['$http', function ($http) {
    var usersArray = [];
    if (usersArray.length === 0) {
        return {
            getJsonData: function () {
                return $http.get('https://api.myjson.com/bins/eznv3')
                    .success(function (data, status, headers, config) {
                        usersArray = data;
                        return data;
                    })
                    .error(function (error, status, headers, config) {
                    });
            }
        }
    }else{
        return usersArray;
    }
}]);

And this is the controller that uses this service:

angular.module("app").controller("ctrl", ["$scope", "getDataService", function ($scope, getDataService) {

    angular.element(document).ready(function () {
            getDataService.getJsonData().then(function (data) {
                $scope.users = data.data;
            });
    });
}]);

Solution

  • You do not need to cache the response of $http.get manually, angularJS itself provides a way to cache the response. Try below code in your getJsonData function of your factory:

    getJsonData: function () {
        return $http.get('https://api.myjson.com/bins/eznv3', {cache: true})
        .success(function (data, status, headers, config) {
              return data;
         })
         .error(function (error, status, headers, config) {
         });
    }
    

    Source: https://docs.angularjs.org/api/ng/service/$http#get

    Read the above document. You will find configurations from there.