Reputation: 681
I got a perfectly working service
this.getcustomers= function() {
var deferred = $q.defer();
$http({
method: 'GET',
url: 'api/customers'
}).then(function success(data) {
deferred.resolve(data.data);
}, function error(error) {
deferred.reject(error);
});
return deferred.promise;
};
How do i add a timeout
to the above. I tried samples from stackoverflow but nothing is working
I need the request to keep trying for 5000 ms and show an error when that time passes.
Adding timeout : timeout|promise
does not work with me.
Any ideas?
Upvotes: 0
Views: 162
Reputation: 320
Here is working link of jsfiddle
function httpRequestHandler () {
var timeout = $q.defer(),
result = $q.defer(),
timedOut = false,
httpRequest;
$timeout(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;
}
Upvotes: 0
Reputation: 4568
What you're looking for is a retry
mechanism, rather than a timeout
. Timeout means "perform an action after X time", in JS anyway.
See the answer here, should be what you're looking for:
AngularJS service retry when promise is rejected
Upvotes: 1