2013-05-27 14 views
1

這是交易。

我在做一個$ http調用時顯示一個微調,但這裏的問題是我有多個調用,所以我在這裏找到的例子沒有幫助。

有沒有人有解決方案呢?

一種堆疊呼叫的方式,以便微調器保持到最後一次呼叫結束?我希望提出我的觀點。

我正在這樣做。

angular.module('moduleName', []). 
factory.("SomeService", function() { 
    return:{ 
     getResources(params) { 
     /* do the $http call */ 
     } 
    } 
}). 
controller("SomeCtrl", function (SomeService) { 
    SomeService.getResources(params) 
}). 
controller("OtherCtrl", function (SomeService) { 
    SomeService.getResources(params) 
}); 

2個控制器可能同時調用服務,可能會得到不同的響應。

回答

6

全部$http在Angular中的調用返回一個承諾。

$q服務沒有Q庫,它是基於所有的花裏胡哨的,但如果你看docs,它確實有一個all方法,可以用來給你的功能你想。

這裏是你如何使用它:

app.controller('HttpController', function($http, $q) { 

    // A hypothetical submit function 
    $scope.submit = function() { 
    // Set a loading variable for use in the view (to show the spinner) 
    $scope.loading = true; 

    var call1 = $http.get(/* ... */); 
    var call2 = $http.get(/* ... */); 
    var call3 = $http.get(/* ... */); 

    $q.all([call1, call2, call3]).then(function(responses) { 
     // responses will be an array of values the individual 
     // promises were resolved to. For this case, we don't 
     // need it, since we only care that they all resolved 
     // successfully. 

     $scope.loading = false; 
    }, function(errorValue) { 
     // If any of the promises is rejected, the error callback 
     // will be resolved with that rejection value, kind of like 
     // an early exit. We want to mark the loading variable 
     // as false here too, and do something with the error. 

     $scope.loading = false; 
    }); 
    }; 
}); 
+0

有沒有辦法做到這一點,如果$ http調用是由不同的控制器? – Charlires

+1

是的,您必須創建一個工廠或服務來爲您管理它。但是,這會做出某些假設,就像電話總是同時發生一樣。如果他們在不同的時間製造並獲得不同的結果,那麼可能會有奇怪的UX擁有一個「全局」加載狀態。 – satchmorun

+0

謝謝,它對我有很大的幫助。 – Charlires

0

使用初始化爲您正在進行的呼叫次數的變量。在AJAX調用的每個回調中,調用一個函數來減少此變量的值,如果它爲零,則刪除微調器。

num_calls = 3; 

function considerRemoveSpinner() { 
    if (--window.num_calls == 0) 
    { 
     removeSpinner(); 
    } 

} 

$http.get("url").success(
    function() { 
     /* regular handler */ 
     considerRemoveSpinner(); 
    } 
); 

/* other ajax calls */ 
+0

這是有道理的,但我希望,角已經有了一些東西。 – Charlires

0

您可以通過使用攔截和傳球一個標誌中的每個API.What的頭做這一切,你需要做的it.Add一個參數每$ http呼叫。

通過使用屬性config.headers {{Parameter}}在攔截器Request方法中捕獲它。在此標誌的基礎上,廣播一個用於顯示等待圖像的事件。