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

时间:2013-11-07 10:37:14

标签: javascript angularjs

我正在使用$http.postnode.js服务器获取数据。我想处理延迟。

我已将超时添加为$http.defaults.timeout = 100;,并且预计错误延迟console.log但是它无效。

示例:

$http.defaults.timeout = 100;
$http.post(url, data).success(function(result) {
    callback(result);
}).error(function(error) {
    console.log("error");
});

我是AngularJS的新手。任何帮助都将不胜感激。

3 个答案:

答案 0 :(得分:4)

$timeout返回承诺。 $http.post也会返回承诺。

所以我会使用$q.allDocuments

参考

$q.all([promise, …])newPromise 所有给定的承诺都会解决newPromise 已经解决了。

我们可以创建一些工厂(或者如果你想改变它,可以使用提供者):

.factory('delay', ['$q', '$timeout',
    function($q, $timeout) {
        return {
            start: function() {
                var deferred = $q.defer();
                $timeout(deferred.resolve, 100);
                return deferred.promise;
            }
        };
    }
]); 

现在在控制器中我们可以编写如下内容:

$q.all([delay.start(), $http.post(url, data)]).then(
    function(results) {
        // .....
    }, function(error) {
        // ....
    });

因此,只有在超时停止时才会得到响应,无论我们从$http.post

获得响应的速度有多快

答案 1 :(得分:1)

AngularJS $ http接受超时作为请求参数之一(更多here

请查看此post,其中说明了如何实现超时功能:

$http.post(url, { timeout: 100 })
        .success(success)
        .error(error);

成功和错误函数接受几个参数:function(data, status, headers, config)。当您收到超时错误时,将执行错误处理程序,其状态将为0

我希望这会有所帮助。

答案 2 :(得分:0)

检查一下:

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