2

Folks,

I have written a service that fetches data from my server in the following fashion:

myApp.factory('CommonHttpService', function($http, $q){
var myUrl;

return{
    query: function(tableName){ 
    //Forming the URl
    myUrl = baseUrl + "?table=" + tableName;

    // Create a deferred object
    var deferred = $q.defer();

    //Calling web api to fetch all rows from table
    $http.get(myUrl).success(function(data){            
        deferred.resolve(data);
    }).error(function(){
        // Sending a friendly error message in case of failure
        deferred.reject("An Error occured while fetching items");
    });

    // Returning the promise object
    return deferred.promise;


}});

My Controller calls it like this:

 // Get entire list
CommonHttpService.query(tableName).then(function(data) { 
   $scope.list = data;                            
}); 

So my question is, in this entire scheme of things I am not sure HOW or WHERE to handle errors. Does the error get handled in deferred.reject().. if so how ?

Or does it get handled after the .then() in the controller.

Ideally I should be displaying some sort of message to the user like "No data found" and itnernally sending the error details to the admin or something

Those who have done, this before and have any bits of advice kindly pass them ON.

Thanks in advnace.

4

1 回答 1

0

然后期望两个功能首先是成功,其次是失败

 CommonHttpService.query(tableName).then(function(data) { 
       $scope.list = data;                            
    },function(error){
    alert("error")
    }); 

You should directly return $http.get which also returns a promise 
--Refactoring --- 
       myApp.factory('CommonHttpService', function($http, $q){
    var myUrl;
    return{
        query: function(tableName){ 

        myUrl = baseUrl + "?table=" + tableName;
        //$http.get also returns a promise 
        return $http.get(myUrl)

    }});

        CommonHttpService.query(tableName).then(function(data) { 
       $scope.list = data;                            
    },function(error){alert(error}); 
于 2013-07-23T14:10:31.473 回答