How to cache an http get service in angularjs?

Published on Author Code Father

Angular’s $http has a cache built in. Just set cache to true in its options:

$http.get(url, { cache: true}).success(...);

or

$http({ cache: true, url: url, method: 'GET'}).success(...);

Or you can implement it yourself using $cacheFactory (especially handly when using $resource):

var cache = $cacheFactory('myCache');

var data = cache.get(someKey);

if (!data) {
   $http.get(url).success(function(result) {
      data = result;
      cache.put(someKey, data);
   });

Comments

comments