How to detect if the $ http request is a cache response or not?

1

In AngularJs, $http has a very useful option of caching the result of a request to a specific url .

For example:

 $scope.getUsers = function () {
       return $http.get('/users', {cache: true})
 }

 $scope.getUsers().then( response => console.log(response.data)); // Faz a requisição

 $scope.getUsers().then( response => console.log(response.data)); // Pega o cache, pois foi feita uma primeira requisição

But now I have a small need: I would like to know when I get a response, whether that response came from a cache or not, and found nothing in the variable response (which is returned in the then parameter) index this.

Is there any way in AngularJS to do this?

    
asked by anonymous 14.07.2018 / 17:00

1 answer

2

I do not think it's possible, at least not with $cacheFactory default. You can use this angular-cache , basically it replaces $cacheFactory with a series of extras .

Another option is to not use { cache: true } and manually manage your cache , an example of slide expiration :

const timeout = 300; // 5 minutos
const cache = $cacheFactory('myCache');

...

let cacheKey = 'e024ecb7-f916-4870-b839-568286659671'
let data = cache.get(cacheKey);
let requestApi = (resolve, reject) => {
    $http.get(url).success(function(result) {
        cache.put(cacheKey, { 
            object: result,
            date: new Date()
        });
        resolve(result);
    });
}
return new Promise((resolve, reject) => {
    if (!data) {
        requestApi(resolve, reject)
    } else {
        var date = new Date();
        var ellapsed = (date - data.date) / 1000
        if (date > timeout) {
            cache.remove(cacheKey);
            requestApi(resolve, reject);
        } else {
            data.date = new Date()
            cache.put(data);
            resolve(data.object);
        }
    }
})
    
17.07.2018 / 14:38