Angular $http Cache  Examples

Real world examples of angularjs $http and $resource cache, including how to work with localStorage and sessionStorage.

Angular’s built-in $http service and it’s $http.get() method do NOT cache responses by default. There are a few different ways you can enable $http caching, below are some helpful examples of each. These examples are ordered in terms of difficult, beginning with what’s easiest and most common.

1. Built-in $http Cache

You can quickly enable caching for the $http service in angularjs by setting the cache config parameter.

$http

$http.get('/request-url', {
    cache: true
}).then(function success(){
    // Success handler
}.catch(function error(){
    // Error handler
});

$resource

To add HTTP caching to an Angular.js $resource object add the cache property to the configuration parameters of a given method/action.

ngApp.factory( 'API', [ '$resource', function( $resource ) {
    return $resource( '/api/endpoint', {}, {
        get: {
            method : 'GET',
            cache : true
        }
    } );
} ] );

This will cache the response of the AJAX request in your users browser, very similar to the way jQuery would handle caching of $.get() requests.

2. Custom Cache with $cacheFactory

If you want more control over what is cached you can transform the objects stored in cache before they are saved, and after they are retreived by passing a $cacheFactory object to the cache paramater instead.

For example, let’s say we wanted to implement an LRU Cache. With this approach we store up to 20 cached requests, and let the system remove the least recently used when the cache is full and a new object is referenced which is not there in cache. This can help with larger HTTP requests that are frequently cached throughout an app, which can potentially overload browser memory.

Bare Bones Usage

var customCache = $cacheFactory.get( 'customCache' );

$http.get('/request-url', {
    cache: customCache
}).then(function success(){
    // Success handler
}.catch(function error(){
    // Error handler
});

This does pretty much the same thing as the built-in use of $cacheFactory by the $http service’s cache option, so it’s really not much use right now. What’s important here is that we can define our own custom rules for how the cache is handled to make sure it is done in an efficient way (and one that we can control).

Real-world $cacheFactory Usage

A better example of where and how you would use these in practice is probably useful here. Let’s say we wanted to implement an LRU Cache, which is a common pattern in Java programming. With this approach we store up to 20 cached requests, and let the system remove the least recently used when the cache is full and a new object is referenced which is not there in cache.

This can very helpful when working with larger HTTP requests that are frequently cachgfhed throughout an app, which can potentially overload browser memory. We can do this by setting $cacheFactory’s capacity parameter to define the number of items that is considered “full”.

var customCache = $cacheFactory.get('customCache', {
    capacity: 20
});

$http.get('/request-url', {
    cache: customCache
}).then(function success(){
    // Success handler
}.catch(function error(){
    // Error handler
});

That’s a little better, and hopefully it should be a little more apparant why and when you would go through the extra effort of working with Angular’s $cacheFactory instead of using $http cache.

3. localStorage or sessionStorage Caching

The cache mechanisms built-in to Angular’s $http and $resource services (provided by $cacheFactory) don’t support the localStorage or sessionStorage Browser API’s. The external Angular-cache module will extend Angular to provide a powerful replacement for $cacheFactory that supports both of these API’s.

Usage Scenarios

Leveraging localStorage and sessionStorage are handy for scenarios where you need to persist data beyond in-memory storage. This includes:

  • You want persistant data that extends beyond a browser session (localStorage)
  • You want persistant data for only a browser session (sessionStorage)
  • Situations where you want to explicitly control the TTL or expiration for browser cache

If you encounter one of these situations then I highly recommend the angular-cache module. Here’s a basic demonstration of how it works, but you should reference the full documentation on GitHub if you decide to work with it.

var customCache = $cacheFactory.get('customCache', {
    capacity: 20
});

$http.get('/request-url', {
    cache: customCache
}).then(function success(){
    // Success handler
}.catch(function error(){
    // Error handler
});

4. Cache Everything $http or $resource

There’s one last $http caching scenario that you may be in. If you want to enable Angular’s built-in caching for every $http and $resource request in an app you can add the following config to your app:

ngApp.config( [ '$httpProvider', function( $httpProvider ) {
    $httpProvider.defaults.cache = true;
} ] );

Where ngApp is the name of the app you’re currently working on/in.

Summary

There are many ways to configure angularjs $http cache, the best approach depends entirely on the scenario and needs that you have specifically. In most cases the $http cache will suffice.

Meet the Author

Kevin Leary, WordPress Consultant

I'm a freelance web developer and WordPress consultant in Boston, MA with 17 years of experience building websites and applications. View a portfolio of my work or request an estimate for your next project.