在 angular 中使用工厂时如何处理 $http 错误

How to handle $http errors when using factories in angular

我有如下所示的控制器和工厂,可以轻松处理成功。但是我该如何处理错误?

控制器

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

与其传递回调,不如选择适当的承诺工作流程。为此,使您的服务方法 return 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');
    });
}]);

"service" 在这种情况下看起来更优雅

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