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
Thanks for the post and update!!
In researching this issue specifically for $resource
, I thought I'd elaborate on what I've found:
$http
request:https://github.com/angular/angular.js/issues/2190 http://code.angularjs.org/1.1.5/docs/api/ngResource.$resource
For those of us on earlier versions, specifically I am using angular 1.0.6, it is possible to edit the source file for angular-resource.js on line 396 you will find the call to $http
where you can add the timeout property yourself for all resource requests.
Since it wasn't mentioned and I had to test Stewie's solution, when a timeout does occur, the way to tell between an error and an abort/timeout is checking the 'status' argument. It will return 0
for timeouts instead of say 404
:
$http.get("/home", { timeout: 100 })
.error(function(data, status, headers, config){
console.log(status)
}
Since there are only a few cases where I need to use a timeout as opposed to setting it globally, I am wrapping the requests in a $timeout
function, like so:
//errorHandler gets called wether it's a timeout or resource call fails
var t = $timeout(errorHandler, 5000);
myResource.$get( successHandler, errorHandler )
function successHandler(data){
$timeout.cancel(t);
//do something with data...
}
function errorHandler(data){
//custom error handle code
}