Cache an HTTP 'Get' service response in AngularJS?
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;
}])
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);
});
}
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.
Check out the library angular-cache if you like $http's built-in caching but want more control. You can use it to seamlessly augment $http cache with time-to-live, periodic purges, and the option of persisting the cache to localStorage so that it's available across sessions.
FWIW, it also provides tools and patterns for making your cache into a more dynamic sort of data-store that you can interact with as POJO's, rather than just the default JSON strings. Can't comment on the utility of that option as yet.
(Then, on top of that, related library angular-data is sort of a replacement for $resource and/or Restangular, and is dependent upon angular-cache.)