I have some angular factories for making ajax calls towards legacy ASP.NET .asmx web services like so:
module.factory('productService', ["$http", function ($http) { return { getSpecialProducts: function (data) { return $http.post('/ajax/Products.asmx/GetSpecialProducs', data); } } } ]);
I'm testing on a local network so response times are "too" good. Is there a smart way of delaying the $http a couple of seconds from making the call to simulate a bad connection?
Or do I need to wrap all calls to the factory methods in a $timeout ?
$timeout(function() { productService.getSpecialProducs(data).success(success).error(error); }, $scope.MOCK_ajaxDelay);
setTimeout . The fn function is wrapped into a try/catch block and delegates any exceptions to $exceptionHandler service. The return value of calling $timeout is a promise, which will be resolved when the delay has passed and the timeout function, if provided, is executed. To cancel a timeout request, call $timeout.
The $http service is a core AngularJS service that facilitates communication with the remote HTTP servers via the browser's XMLHttpRequest object or via JSONP. For unit testing applications that use $http service, see $httpBackend mock. For a higher level of abstraction, please check out the $resource service.
The $timeout service can be used to call another JavaScript function after a given time delay. The $timeout service only schedules a single call to the function. For repeated calling of a function, see $interval later in this text.
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.
The new chrome device emulator has a network throttling function:
To get there: In Google Chrome, press F12 to open the Developer Tools. Then, on the top left corner, click the "Toggle device mode" icon (left to the "Elements" menu).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With