sisimh sisimh - 1 year ago 65
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,

$, 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 Source

From the docs:

Only GET and JSONP requests are cached.$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);
    } else {
      $'path/to/resource', postData).then(function(response){
        cache[hash] = 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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download