2

I have a controller and factory like below and can easily handle success..But how can I handle errors?

Controller

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

Factory

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 Answers 2

4

Instead of passing callbacks around, prefer proper promises workflow. For this make your service methods 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;
});

Then use promise API to handle success (then callback) and errors (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');
    });
}]);
Sign up to request clarification or add additional context in comments.

Comments

1

"service" looks more elegantly in this case

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.