-
-
Save adnan-i/5014277 to your computer and use it in GitHub Desktop.
Workaround for $httpProvider.defaults
As discussed here http://stackoverflow.com/a/15020611/1095616, it is not possible to set default timeout in $httpProvider.
This gist offers a workaround.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!doctype html> | |
<html ng-app="myApp"> | |
<head> | |
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.5/angular.min.js"></script> | |
</head> | |
<body> | |
<div ng-controller="TodoCtrl"> | |
<button ng-click="beQuickOrBeDead()">Fetch with 100ms timeout</button> | |
<button ng-click="neverEndingStory()">Fetch with default timeout</button> | |
<p>{{status}}</p> | |
</div> | |
<script> | |
var myApp = angular.module('myApp', []); | |
// this custom config could actually be a part of a more general app-level config | |
// so that you need to inject only one global config | |
myApp.value('http_defaults', { | |
timeout: 150 | |
}); | |
myApp.controller('TodoCtrl', function ($scope, $http, http_defaults) { | |
$scope.status = "N/A"; | |
$scope.neverEndingStory = function () { | |
$scope.status = "N/A"; | |
console.log($http.defaults); // The value is set to 150 but it doesn't affect the .get | |
console.log(http_defaults); // Custom config object for http calls | |
// in case you need to change the default values for this specific request | |
// angular.extend(http_defaults, {timeout: 300}); | |
$http.get("/home", http_defaults) | |
.success(success) | |
.error(error); | |
}; | |
$scope.beQuickOrBeDead = function () { | |
$scope.status = "N/A"; | |
console.log($http.defaults); // The value is set to 150 but it doesn't affect the .get | |
$http.get("/home", { timeout: 100 }) | |
.success(success) | |
.error(error); | |
}; | |
function success() { | |
$scope.status = "OK"; | |
console.log("Request ok"); | |
} | |
function error() { | |
$scope.status = "NOT OK"; | |
console.log("Request not ok"); | |
} | |
}); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Actually this is not a work around. It is intended behaviour - you can set the config for each $http call. A real work around for the problem of globally setting the timeout for all your $http calls in your AngularJS app would be to have a central service, i.e. that you hide $http calls behind your very own $restService which is not only for this a good idea, but for such things as an application wide facility for changing the baseUrl etc. as well.