Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle the delay in $http.post in AngularJS?

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.

like image 275
karthick Avatar asked Nov 07 '13 10:11

karthick


2 Answers

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

like image 77
Maxim Shoustin Avatar answered Oct 25 '22 17:10

Maxim Shoustin


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.

like image 2
Tom Avatar answered Oct 25 '22 18:10

Tom