angularjs – 如何在$http承诺中抛出错误

前端之家收集整理的这篇文章主要介绍了angularjs – 如何在$http承诺中抛出错误前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个角度服务,包装我的其余api调用并返回$http承诺.

我的问题是如何抛出一个错误,以便调用触发.error方法的promise?我不想抛出错误,因为我希望它在调用函数中使用.success / .error而不是在它周围执行try catch块.

myFunction: function(foo)
   if (foo) {
      return $http.put(rootUrl + '/bar',{foo: foo});
   }
   else {
      //what do I return here to trigger the .error promise in the calling function
   }

解决方法

首先在您的服务中注入$q-service.然后在你的其他地方:

else {
     var deferred = $q.defer();
     deferred.reject("reject reason,foo was false");
     return deferred.promise;
}

不像Blazemonger那样聪明,但它很快就能做到.

猜你在找的Angularjs相关文章