简体   繁体   中英

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.

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.

Check this one :

angular.module('MyApp', [])
  .config(['$httpProvider', function($httpProvider) {
    $httpProvider.defaults.timeout = 5000;
}]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM