2012-09-24 57 views
1

我正在研究一個大型的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 ... 

    } 
    }; 

}); 
+1

一種方法是使用本文中描述的$ httpProvider.responseInterceptors進行操作:http://stackoverflow.com/questions/11786764/track-to-see-when-a-view-changes-in-angularjs。也請看看Dan的答案:http://stackoverflow.com/a/11870892/1207991 – Gloopy

回答

0

在我們的代碼庫,我們剛剛在做

$scope.flags.loading = true; 
$http(...).success(function(){ 
    $scope.flags.loading = false; 
}); 

是的,這是有點簡單,但並不是所有的查詢要求裝載覆蓋(如分頁或刷新期間)。這就是爲什麼我們選擇不使用裝飾器。

但是,讓我們說你想,我可以想到一些這樣做的方法。讓我們說你和我們一樣,把你的旗幟放在一個物體上。然後你可以使用聯想到你的優點:

MyService.flags = $scope.flags 
... (inside the service) ... 
this.flags.loading = true/false; 

通過建立基準作爲服務的屬性,你可以做所有的狀態下,從服務中切換,避免塞滿您的控制器。同樣,這可能會造成2個或更多的關係查詢衝突(第一個查詢在第二個查詢完成之前完成並刪除加載狀態)的可能缺點。

因此,我們一直在找到與設置國旗。我們並不真正檢查「加載」,我們只是檢查數據或使用成功回調。

相關問題