Resource and cache AngularJS factory

I implemented the 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 consume this in the controller as follows: -

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

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

This works great. Now I need to cache the data from the api in the CandidateService Factory so that it does not load eveytime. I move between controllers.

So, I thought that 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 can't get it to work. I think this has something to do with angular Factory, which is a single.

Is my approach correct for implementing caching?

+4
source share
1 answer

$cacheFactory. . http://docs.angularjs.org/api/ng. $CacheFactory

$http- :

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

URL- , :

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

$ :

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

:

$httpDefaultCache.removeAll();

: $http

+8

All Articles