Delay an angular.js $http service

前端 未结 8 1135
感动是毒
感动是毒 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.

提交回复
热议问题