如何使成功的Angular JS $ http.get()承诺失败 [英] How to fail a successful Angular JS $http.get() promise

查看:100
本文介绍了如何使成功的Angular JS $ http.get()承诺失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何拒绝或失败成功的$ http.get()承诺?当我收到数据时,我将对它运行验证器,如果数据没有必需的属性,我将拒绝该请求.我知道在兑现诺言之后我可以做,但是尽快拦截错误似乎是个好主意. 我熟悉$ q的好处,但真的想继续使用$ http.

How do I reject or fail a successful $http.get() promise? When I receive the data, I run a validator against it and if the data doesn't have required properties I want to reject the request. I know I can do after the promise is resolved, but it seems like a good idea to intercept errors as soon as possible. I'm familiar with the benefits of $q, but really want to continue using $http.

推荐答案

您可以通过将$q.reject("reason")返回到下一个链接的.then来拒绝任何承诺.

You can reject any promise by returning $q.reject("reason") to the next chained .then.

$http相同,它返回一个承诺-可能如下:

Same with $http, which returns a promise - this could be as follows:

return $http.get("data.json").then(function(response){
  if (response.data === "something I don't like") {
    return $q.reject("bad data");
  }
  return response.data;
}

这可以简单地在服务中完成,该服务使用上面指定的.then预先处理响应,并返回一些数据-或拒绝.

This could simply be done within a service, which pre-handles the response with the .then as specified above, and returns some data - or a rejection.

如果要在应用程序级别执行此操作,可以使用$ http

If you want to do this at an app-level, you could use $http interceptors - this is just a service that provides functions to handle $http requests and responses, and allows you to intercept a response and return either a response - same or modified - or a promise of the response, including a rejection.

.factory("fooInterceptor", function($q){
  return {
    response: function(response){
      if (response.data === "something I don't like") {
        return $q.reject("bad data");
      }
      return response;
    }
  }
});

与上面相同的想法-只是在不同的级别上.

Same idea as above - except, at a different level.

请注意,要注册拦截器,您需要在.config内执行此操作:

Note, that to register an interceptor, you need to do this within a .config:

$httpProvider.interceptors.push("fooInterceptor");

这篇关于如何使成功的Angular JS $ http.get()承诺失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆