4

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?

2

1 Answer 1

8

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.