从 $http.success 返回错误



我在 Angular 中工作,当结果在 .success() 中解析时,我需要向链下的承诺表示错误。

我从控制器调用服务中的函数,例如

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

myFunction 是这样的

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

基于某些条件,我需要让 .then() 执行 errorCallback,即使触发了 $http.get().success()。如何使其看起来像$http收到错误?

您需要执行的一些修复方法是使用 then 而不是success $http 上的函数。

then成功的回调中,您可以执行return $q.reject(errorData)来拒绝链下的承诺。

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返回原始$http承诺,而then返回使用返回值成功和错误回调进行解析的承诺。

最新更新