Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS $http cache expiration time

Tags:

angularjs

Can you set an expiration time for Angular's $http default caching system ? I would like that an URL stays in the cache for 1 minute, so that any requests made to it after 1 minute grabs fresh data from the server.

like image 914
Adrian Neatu Avatar asked Jan 16 '14 15:01

Adrian Neatu


2 Answers

An expiration time-based cache implementation for AngularJS might look like this:

MyAngularApp.factory('cache', function($cacheFactory) {    
    const cache = $cacheFactory('expire-cache');

    function get(key, defaultValue = null, expire = null) {    
        let cached = cache.get(key);
        let expired = cached && cached.expire > 0 && cached.expire < performance.now() - cached.created;
       
        if (!cached || expired) {
            cached = {
                value: typeof (defaultValue) === 'function' ? defaultValue() : defaultValue,
                expire: expire,
                created: performance.now()
            }

            if (cache.value !== null && 
                cache.value !== undefined) {

                cache.put(key, cached);
            }
        }
        
        return cache.value;
    }

    return {
        get: get,
        remove: function remove(key) { cache.remove(key) },
        clear: function clear() { cache.removeAll() },
    };    
});

The possible method calls would be these:

read = cache.get('keyName1', 'my permanent value');
read = cache.get('keyName2', 'my static value for 5 secs', 5000);
read = cache.get('keyName3', () => 'my on time value for 5 secs', 5000);

cache.remove('keyName1'); /* Remove one */

cache.clear(); /* Remove all */
like image 57
Sergio Cabral Avatar answered Sep 27 '22 21:09

Sergio Cabral


There is no way to set the expiration time. But you can do it manually. You have to access the $http cache:

var cache = $cacheFactory.get('$http');

and remove the url that is cached by:

cache.remove(theUrl);

See documentation for more information.

like image 25
michael Avatar answered Sep 27 '22 22:09

michael