How to fail a successful Angular JS $http.get() promise

老子叫甜甜 提交于 2019-12-11 23:27:49

问题


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.


回答1:


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

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;
}

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.

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.

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

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



回答2:


You can use AngularJS interceptors. But you still need to use $q in them because $http uses $q.

Here is a useful article about interceptors.



来源:https://stackoverflow.com/questions/29178505/how-to-fail-a-successful-angular-js-http-get-promise

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!