簡體   English   中英

如何處理AngularJS中$ http.post的延遲?

[英]How to handle the delay in $http.post in 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新手。 任何幫助將不勝感激。

$timeout返回promise。 $http.post返回promise。

所以我會使用$q.all 文件

參考

$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獲得響應的速度有多快

AngularJS $ http接受超時作為請求參數之一(更多這里

請看一下這篇文章 ,它解釋了如何實現超時功能:

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

成功和錯誤函數接受幾個參數: function(data, status, headers, config) 當您收到超時錯誤時,將執行錯誤處理程序,其狀態將為0

我希望這會有所幫助。

檢查一下:

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