I know I can set a timeout each and every time:
$http.get('path/to/service', {timeout: 5000});
... but I want to set a global timeout to keep my code DRY.
AngularJS $http had timeout option and it worked just great. Yup, Im aware of that.
$http is an AngularJS service for reading data from remote servers.
This '$timeout' service of AngularJS is functionally similar to the 'window. setTimeout' object of vanilla JavaScript. This service allows the developer to set some time delay before the execution of the function.
The problem is as follows, $http. get is asynchronous, before the response is fetched, the function returns. Therefore the calling function gets the data as empty string.
This is possible with bleeding-edge angular.js (tested with git master 4ae46814ff).
You can use request http interceptor. Like this.
angular.module('yourapp') .factory('timeoutHttpIntercept', function ($rootScope, $q) { return { 'request': function(config) { config.timeout = 10000; return config; } }; });
And then in .config inject $httpProvider and do this:
$httpProvider.interceptors.push('timeoutHttpIntercept');
UPDATED: $http will not respect default setting for timeout set it in httpProvider (see the comments). Possible workaround: https://gist.github.com/adnan-i/5014277
Original answer:
angular.module('MyApp', []) .config(['$httpProvider', function($httpProvider) { $httpProvider.defaults.timeout = 5000; }]);
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