I am using $http.post
to get the data from node.js
server. I want to handle the delay.
I had added timeout as $http.defaults.timeout = 100;
and expected to console.log
the delay in error but it is not working.
Example:
$http.defaults.timeout = 100;
$http.post(url, data).success(function(result) {
callback(result);
}).error(function(error) {
console.log("error");
});
I am new to AngularJS
. Any help will be grateful.
The $timeout
returns promise. The $http.post
returns promise as well.
So I would use $q.all
. Documents
Reference
$q.all([promise, …])
→ newPromise
newPromise
will resolve once all the given promises have
been resolved.
We can create some factory (or if you want to change it use can use provider):
.factory('delay', ['$q', '$timeout',
function($q, $timeout) {
return {
start: function() {
var deferred = $q.defer();
$timeout(deferred.resolve, 100);
return deferred.promise;
}
};
}
]);
and now in controller we can write something like:
$q.all([delay.start(), $http.post(url, data)]).then(
function(results) {
// .....
}, function(error) {
// ....
});
So you get response only if timeout stopped no matter how quick we get response from $http.post
AngularJS $http accepts timeout as a one of the request parameters (more here)
Please have a look at this post which explains how to implement the timeout functionality:
$http.post(url, { timeout: 100 })
.success(success)
.error(error);
Success as well as error functions accepts several parameters: function(data, status, headers, config)
. When you get a timeout error, error handler will be executed and its status will be 0
.
I hope that will help.
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