Caching GET Requests Using Angular $resource

When designing web apps for mobile, two factors that we take for granted in a browser must be addressed, namely, speed and bandwidth usage. Making a request to the server for the same data can significantly slow down an app, and increase the bandwidth usage. The solution to this problem is caching, and starting in Angular 1.2, the $resource object comes with a cache parameter to simplify the process of caching a GET request.

Using the cache parameter requires adding only a single line of code to your $resource service.

.service('Products', function ($resource) {
    return $resource(/product/:id',
        {id:'@id'},
        {
            query: {
                method: 'GET',
                cache: true
            }
         }
    );
});

Now only the first GET request will actually hit the server, and continual requests will be retrieved from the $cacheFactory. Depending on the kind of application you are developing, you could be finished here, however many applications have data that changes based on user interactions. If that is the case, you will need a way to tell the cache to reload itself with the newest data from the server. This can be accomplished by creating a simple factory to remove a key from the $cacheFactory.

.factory('Cache', function ($cacheFactory) {
    var $httpDefaultCache = $cacheFactory.get('$http');
 
    return {
        invalidate: function (key) {
            $httpDefaultCache.remove(key);
        }
    }
});

Anytime your $resource has changed, you can reload the cache by calling:

// to reload the entire cache
Cache.invalidate('/api/v1/product');
// to reload a single entry
Cache.invalidate('/api/v1/product/' + entry.id);

Thanks for reading, comment below if you have any questions or comments.