return an error from $http.success

2019-09-17 16:24发布

问题:

I am working in Angular and I need to signify an error to a promise further down the chain when the result is being resolved in .success().

I call a function in my service from my controller like

myService.myFunction().then(
   function(results){
      // do success stuff
   },
   function(err){
      // do failure stuff
   });

myFunction is something like

myFunction(){
    return $http.get('url')
       .success(function(results){})
       .error(function(err){})
}

Based on certain conditions, I need to have .then() execute the errorCallback even though $http.get().success() was triggered. How can I make it look like $http received an error?

回答1:

Some fixes that you need to do to achieve this would be use the then instead of success function on $http.

And in the then success callback you can do a return $q.reject(errorData) to reject the promise down the chain.

return $http.get('url').then(function(results){
    if(condition) {
      return $q.reject(errorData);
    }
    return result.data;  //then callback get a object with properties
},function(error) {
      return $q.reject(error);
  })

success returns the original $http promise whereas then returns a promise that gets resolved with the return value of success and error callback.