3

I'm new to angular and I need to cache data to increase the performance. For this I'm using $cacheFactory by Angular.

When I try,

myApp.factory('myCache', function($cacheFactory) {
 return $cacheFactory('myData');
});

With

myApp.controller('MyMain', ['$scope', '$http', 'myCache',
 function ($scope, $http, myCache) {
   var cache = myCache.get('myData');
   if (cache) {
     $scope.variable = cache;
   }
   else {
     $http.get('http://www.example.com/path/to/api/endpoint')
       .success(function(data) {
         $scope.variable = data;

         myCache.put('myData', data);
       }
    );
  }
}

This works fine, but it only caches one set of data, as I want to cache multiple set of data I uses

myApp.factory('myCache', function($cacheFactory) {
 return {
  get : function(cacheKey){
    return $cacheFactory(cachekey);
     }
   }
});

So if I go to another page I can cache another set of data like this,

myApp.controller('MyMain', ['$scope', '$http', 'myCache',
 function ($scope, $http, myCache) {
   var cache = myCache.get('myData2');
   if (cache) {
     $scope.variable = cache;
   }
   else {
     $http.get('http://www.example.com/path/to/api/endpoint')
       .success(function(data) {
         $scope.variable = data;

         myCache.put('myData2', data);
       }
    );
  }
}

etc.

However in the latter way although it doesn't give any error no data is returned and no ajax call is made to cache the data.

How can I fix this? And cache multiple sets of data using $cacheFactory?

1 Answer 1

6

If your URL is unique for the data that you are querying, then you should use the built in cache inside $http:

$http.get('http://www.example.com/path/to/api/endpoint', { cache: true }).success(...

This will cache based on the uniqueness of the URL parameter in cacheProvider for you.

Here is the documentation for this functionality.

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

1 Comment

Thanks this works fine. I think modifying this answer for an $http will also work as well stackoverflow.com/a/14094714

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.