如何在角度使用工厂时处理$ http错误

时间:2016-04-16 19:56:49

标签: angularjs angular-http

我有一个像下面这样的控制器和工厂,可以轻松处理成功。但我怎样才能处理错误?

控制器

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;
});

2 个答案:

答案 0 :(得分:4)

不要传递回调,而是选择正确的承诺工作流程。为此,您的服务方法将返回promise objects

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;
});

然后使用promise API来处理成功(then回调)和错误(catch):

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 :(得分:1)

在这种情况下,

“服务”看起来更优雅

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);