Delay an angular.js $http service

前端 未结 8 1117
感动是毒
感动是毒 2021-01-31 16:32

I have some angular factories for making ajax calls towards legacy ASP.NET .asmx web services like so:

module.factory(\'productService\', [\"$http\",
function ($         


        
相关标签:
8条回答
  • 2021-01-31 16:54

    Interesting question!

    As you mentioned yourself, $timeout is the most logical choice for a delayed call. Instead of having $timeout calls everywhere, you could push a response interceptor that wraps the $http promise in a $timeout promise, as conceptually outlined in the documentation of $http, and register it in one of your configuration blocks. This means all $http calls are affected by the $timeout delay. Something along the lines of:

    $httpProvider.interceptors.push(function($timeout) {
        return {
            "response": function (response) {
                return $timeout(function() {
                    return response;
                }, 2500);
            }
        };
    });
    

    As a bonus to your "to simulate a bad connection?", you could reject or do absolutely nothing randomly, too. Heh heh heh.

    0 讨论(0)
  • 2021-01-31 16:56

    While @stevuu's answer is correct, the syntax has changed in the newer AngularJS versions since then. The updated syntax is:

    $httpProvider.interceptors.push(["$q", "$timeout", function ($q, $timeout) {
      function slower(response) {
        var deferred = $q.defer();
        $timeout(function() {
            deferred.resolve(response);
        }, 2000);
        return deferred.promise;
      }
      return {
        'response': slower
      };
    }]);
    
    0 讨论(0)
提交回复
热议问题