2016-04-16 5 views
2

私は以下のようなコントローラと工場を持っており、簡単に成功を処理できます。しかし、どうやってエラーを処理できますか?

コントローラ

app.controller("draftsCtrl", ["$scope", "DashboardFactory", function ($scope, DashboardFactory) { 
    DashboardFactory.drafts(function (successCallback) { 
     $scope.rooms listings= successCallback; 
    }); 
}]); 

工場

app.factory('DashboardFactory', function ($http) { 
    var DashboardFactory = {}; 

    DashboardFactory.active_listings = function (successCallback) { 
     $http.get('active.json').success(successCallback); 
    } 

    DashboardFactory.inactive_listings = function (successCallback) { 
     $http.get('inactive.json').success(successCallback); 
    } 

    DashboardFactory.drafts = function (successCallback) { 
     $http.get('drafts.json').success(successCallback); 
    } 
    return DashboardFactory; 
}); 

答えて

4

代わりに周りのコールバックを渡す、適切な約束のワークフローを好みます。

app.factory('DashboardFactory', function ($http) { 
    var DashboardFactory = {}; 

    DashboardFactory.active_listings = function() { 
     return $http.get('active.json'); 
    } 

    DashboardFactory.inactive_listings = function() { 
     return $http.get('inactive.json'); 
    } 

    DashboardFactory.drafts = function() { 
     return $http.get('drafts.json'); 
    } 

    return DashboardFactory; 
}); 

次に成功(thenコールバック)とエラー(catch)を処理するために、約束のAPIを使用します:

app.controller("draftsCtrl", ["$scope", "DashboardFactory", function ($scope, DashboardFactory) { 
    DashboardFactory.drafts().then(function (response) { 
     $scope.rooms_listings = response.data; 
    }) 
    .catch(function() { 
     console.log('Error ocurred'); 
    }); 
}]); 
1

"サービス" は、この場合には、よりエレガントに見える

このために、あなたのサービスメソッドが promise objectsを返すよう
function DashboardFactory($http) { 
    this.active_listings = function() { 
     return $http.get('active.json'); 
    }; 

    this.inactive_listings = function() { 
     return $http.get('inactive.json'); 
    }; 

    this.drafts = function() { 
     return $http.get('drafts.json'); 
    }; 
}); 

DashboardFactory.$inject = ['$http']; 

app.factory('DashboardFactory', DashboardFactory); 
関連する問題