简体   繁体   English

如何处理AngularJS中$ http.post的延迟?

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

I am using $http.post to get the data from node.js server. 我使用$http.postnode.js服务器获取数据。 I want to handle the delay. 我想处理延迟。

I had added timeout as $http.defaults.timeout = 100; 我添加了超时,因为$http.defaults.timeout = 100; and expected to console.log the delay in error but it is not working. 并期望console.log延迟出错,但它无法正常工作。

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 . 我是AngularJS新手。 Any help will be grateful. 任何帮助将不胜感激。

The $timeout returns promise. $timeout返回promise。 The $http.post returns promise as well. $http.post返回promise。

So I would use $q.all . 所以我会使用$q.all Documents 文件

Reference 参考

$q.all([promise, …])newPromise newPromise will resolve once all the given promises have been resolved. $q.all([promise, …])newPromise newPromise将在解决所有给定的承诺后解决。

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 因此,只有在超时停止时才会得到响应,无论我们从$http.post获得响应的速度有多快

AngularJS $http accepts timeout as a one of the request parameters (more here ) AngularJS $ http接受超时作为请求参数之一(更多这里

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) . 成功和错误函数接受几个参数: function(data, status, headers, config) When you get a timeout error, error handler will be executed and its status will be 0 . 当您收到超时错误时,将执行错误处理程序,其状态将为0

I hope that will help. 我希望这会有所帮助。

Check this one : 检查一下:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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