Cache an HTTP 'Get' service response in AngularJS? Cache an HTTP 'Get' service response in AngularJS? ajax ajax

Cache an HTTP 'Get' service response in AngularJS?


Angular's $http has a cache built in. According to the docs:

cache – {boolean|Object} – A boolean value or object created with $cacheFactory to enable or disable caching of the HTTP response. See $http Caching for more information.

Boolean value

So you can set cache to true in its options:

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

or, if you prefer the config type of call:

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

Cache Object

You can also use a cache factory:

var cache = $cacheFactory('myCache');$http.get(url, { cache: cache })

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);   });}


I think there's an even easier way now. This enables basic caching for all $http requests (which $resource inherits):

 var app = angular.module('myApp',[])      .config(['$httpProvider', function ($httpProvider) {            // enable http caching           $httpProvider.defaults.cache = true;      }])


An easier way to do this in the current stable version (1.0.6) requires a lot less code.

After setting up your module add a factory:

var app = angular.module('myApp', []);// Configure routes and controllers and views associated with them.app.config(function ($routeProvider) {    // route setups});app.factory('MyCache', function ($cacheFactory) {    return $cacheFactory('myCache');});

Now you can pass this into your controller:

app.controller('MyController', function ($scope, $http, MyCache) {    $http.get('fileInThisCase.json', { cache: MyCache }).success(function (data) {        // stuff with results    });});

One downside is that the key names are also setup automatically, which could make clearing them tricky. Hopefully they'll add in some way to get key names.