Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS $resource & cache factory

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?

like image 754
Yashvit Avatar asked Feb 16 '23 05:02

Yashvit


1 Answers

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

like image 184
Thomas Pons Avatar answered Feb 17 '23 20:02

Thomas Pons