How do I detect whether the $http request is a cache response or not?

Asked

Viewed 59 times

1

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

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 receive an answer, if that answer came from a cache or not, and I did not find anything in the variable response (which is returned in the parameter then) that underlies this.

Is there any way in Angularjs to do that?

1 answer

2

I don’t believe it’s possible, at least not with the $cacheFactory standard. You may use this lib angular-cache, basically it replaces the $cacheFactory with a lot of extras.

Another option is not to use the { cache: true } and manually manage your cache, follows 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);
        }
    }
})

Browser other questions tagged

You are not signed in. Login or sign up in order to post.