javascript 如何处理 AngularJS 中 $http.post 的延迟?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19833694/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to handle the delay in $http.post in AngularJS?
提问by karthick
I am using $http.post
to get the data from node.js
server. I want to handle the delay.
我正在使用$http.post
从node.js
服务器获取数据。我想处理延迟。
I had added timeout as $http.defaults.timeout = 100;
and expected to console.log
the delay in error but it is not working.
我已经按照$http.defaults.timeout = 100;
预期添加了超时时间来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
. Any help will be grateful.
我是新手AngularJS
。任何帮助将不胜感激。
回答by Maxim Shoustin
The $timeout
returns promise. The $http.post
returns promise as well.
该$timeout
回报的承诺。该$http.post
收益承诺为好。
So I would use $q.all
. Documents
所以我会使用$q.all
. 文件
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
回答by Tom
AngularJS $http accepts timeout as a one of the request parameters (more here)
AngularJS $http 接受超时作为请求参数之一(更多在这里)
Please have a look at this postwhich 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
.
成功和错误函数接受几个参数:function(data, status, headers, config)
. 当您收到超时错误时,将执行错误处理程序,其状态将为0
。
I hope that will help.
我希望这会有所帮助。
回答by Prasad Shigwan
Check this one :
检查这个:
angular.module('MyApp', [])
.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.timeout = 5000;
}]);