我正在研究一個大型的AngularJS應用程序,我試圖將所有的Ajax代碼封裝到控制器從中獲取數據的各種服務中。問題圍繞着需要知道任何ajax調用的狀態並向用戶顯示正確的信息。可能沒有找到數據,當前正在加載的數據或發生的阻止數據加載的錯誤。用戶需要顯示加載消息,「找不到數據」消息或錯誤消息。如何讓我的控制器知道加載數據的狀態?
比方說,我有一個ProjectService
。理想情況下,如果有一種叫做getAllProjects
的方法,它會返回一個項目數組。但那樣我就不知道服務器通信發生了什麼。
那麼如何讓控制器知道數據是加載,加載還是發生錯誤?我能想到的最好方法是使用下面僞代碼中的回調。有沒有更好的方法來完成這樣的事情或我可能忽略的任何事情?
謝謝。
app.controller("ProjectController", function($scope, ProjectService){
// Set the initial/default status
$scope.loadStatus = "loading";
// Return an empty array initially that will be filled with
// any data that is returned from the server
// The callback function will be executed when the ajax call is finished
$scope.projects = ProjectService.getProjects(function(status){
// Alert the controller of a status change
setStatus(status);
});
function setStatus(){
$scope.loadStatus = status;
// ... update the view or whatever is needed when the status changes....
}
});
app.service("ProjectService", function($resource){
return {
getAllProjects: function(){
// ... load and return the data from the server ...
}
};
});
一種方法是使用本文中描述的$ httpProvider.responseInterceptors進行操作:http://stackoverflow.com/questions/11786764/track-to-see-when-a-view-changes-in-angularjs。也請看看Dan的答案:http://stackoverflow.com/a/11870892/1207991 – Gloopy