AngularJS $resource & cache factory

Yashvit picture Yashvit · Sep 21, 2013 · Viewed 12.1k times · Source

I have implemented angular $resource with custom functions and parameters as follows:-

.factory('CandidateService', ['$resource', function ($resource) {
    return $resource("api/:action/:id", {},
    {
        'getCandidates': { method: "GET", params: { action: "Candidate" }, isArray: true },
        'getCandidate': { method: 'GET', params: { action: "Candidate", id: "@id" } }
    });
}]);

And I am consuming this in the controller as follows:-

.controller('Controller', ['CandidateService', function ($scope, CandidateService) {
  $scope.candidateList = [];

  CandidateService.getAll(function (data) {
    $scope.candidateList = data;   
  });
}]);

This is working absolutely fine. Now I need to cache the data from the api into the CandidateService Factory so it is not loaded eveytime I move between the controllers.

So I thought i would do something as follows:-

.factory('CandidateService', ['$resource', function ($resource) {
    var Api = $resource("api/:action/:id", {},
    {
        'getCandidates': { method: "GET", params: { action: "Candidate" }, isArray: true },
        'getCandidate': { method: 'GET', params: { action: "Candidate", id: "@id" } }
    });

    var candidateDataLoaded = false;
    var candidateData = [];

    return {
        getCandidates: function () {
            if (!candidateDataLoaded) {
                Api.getAll(function (data) {
                    angular.copy(data, candidateData);
                });
            }
            return candidateData;
        }
    }

}]);

But I just cant get this to work. I think it has something to do with angular factory being a singleton.

Is my approach correct to implement the caching?

Answer

Thomas Pons picture Thomas Pons · Sep 22, 2013

You can use the $cacheFactory object. See : http://docs.angularjs.org/api/ng.$cacheFactory

You can cache $http request like that :

var $httpDefaultCache = $cacheFactory.get('$http');

If you want to retrieve a specific url in cache do :

var cachedData = $httpDefaultCache.get('http://myserver.com/foo/bar/123');

$You can clear the cache too :

$httpDefaultCache.remove('http://myserver.com/foo/bar/123');

or :

$httpDefaultCache.removeAll();

Complete post here : Power up $http with caching