Proper handling of AngularJS $http Timeouts
This code shows how to integrate a Promise with the $http call to get proper notification when a request has exceeded the timeout.
by samu_eyes
HTML
<div ng-app="ExampleApp">
<div ng-controller="DemoController">
<div class="status">Status: {{status}}</div>
<div class="response">Response: {{response | json}}</div>
<hr />
<label>
Delay: <input ng-model="delay" />
</label>
<br />
<label>
Timeout: <input ng-model="timeout" />
</label>
<br />
<button ng-click="makeRequest()">Make Ajax Request</button>
<p>Change the timeout to be less than the delay to observe timeout mechanics.</p>
</div>
</div>
JavaScript
angular.module('ExampleApp', [])
.controller('DemoController', function ($scope, $http, $q) {
$scope.timeout = 5;
$scope.delay = 3
function createData () {
var result = "";
result += "json=" + encodeURI(JSON.stringify({
text : [
"My timeout is ",
$scope.timeout,
" seconds and my delay is ",
$scope.delay,
" seconds."
].join('')
}));
result += '&delay=' + $scope.delay
return result;
}
function httpRequestHandler () {
var timeout = $q.defer(),
result = $q.defer(),
timedOut = false,
httpRequest;
setTimeout(function () {
timedOut = true;
timeout.resolve();
}, (1000 * $scope.timeout));
httpRequest = $http({
method : 'post',
url: '/echo/json/',
data: createData(),
cache: false,
timeout: timeout.promise
});
httpRequest.success(function(data, status, headers, config) {
result.resolve(data);
});
httpRequest.error(function(data, status, headers, config) {
if (timedOut) {
result.reject({
error: 'timeout',
message: 'Request took longer than ' + $scope.timeout + ' seconds.'
});
} else {
result.reject(data);
}
});
return result.promise;
}
$scope.makeRequest = function () {
$scope.status = 'Requesting';
$scope.response = '';
...