sisimh sisimh - 1 month ago 13
AngularJS Question

$http service cache when the method is post

when I set the $http to cache requests, I still see duplicate requests (with the same url and same data) sent to the server from browser network,

$http.post(url, data, {cache:true} ).success(function(response) {


is this a right behaviour? can we cache post requests? and is this the right way to do so or should I be doing it manually with the $cachefactory ?

Answer

From the docs:

Only GET and JSONP requests are cached.

https://docs.angularjs.org/api/ng/service/$http

If you want to cache POST-requests you would have to do it manually. You will need to make a service/factory that caches responses and serves as a layer before $http. You can use $cacheFactory or just a plain object.

function cacheService($http, $q){

  var cache = {};

  this.callSomething = function(postData){
    let deferred = $q.defer();
    let hash = angular.toJson(postData);
    if(cache[hash]){
      deferred.resolve(cache[hash]);
    } else {
      $http.post('path/to/resource', postData).then(function(response){
        cache[hash] = response;
        deferred.resolve(response);
      });
    }

    return deferred.promise;
  }
}

This is a simple example, you could of course use the same principle and make a more generalized service that takes an URL, postData and a cache object and returns a function that does the request and caches it.