9

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.

1
  • You should use .then(function(response) { }) with $http which returns a promise. Commented Jul 7, 2016 at 8:50

3 Answers 3

4

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

Sign up to request clarification or add additional context in comments.

Comments

2

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.

1 Comment

@Tom, Thanks for the handy solution. When ll the delay happen if we pass the timeout parameter as you demonstrated? before or after the request?
0

Check this one :

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.