私は大規模な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 ...
}
};
});