2016-04-16 1 views
2

umgehen Ich habe einen Controller und Fabrik wie unten und kann leicht mit Erfolg umgehen .. Aber wie kann ich mit Fehlern umgehen?

-Controller

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

Fabrik

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

Antwort

4

Statt um Rückrufe zugeben, bevorzugen richtigen Versprechen Workflow. Dazu Ihre Service-Methoden promise objects zurückkehren machen:

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

Dann Versprechen API Erfolg zu behandeln (then Rückruf) und Fehler (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

"Service" sieht eher elegant in diesem Fall

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