简体   繁体   English

$ http / $ q / promise问题(以角度显示)

[英]$http/$q/promise Questions (in Angular)

I can't seem to wrap my head around when $q/$http should trigger the onReject block. 当$ q / $ http应该触发onReject块时,我似乎无法onReject

Let's say I have a basic call: 假设我有一个基本电话:

$http.get('/users')
  .then(function(res) {
    return res.data;
  }, function(err) {
    console.log(err);
  });

If I get a 500 Internal Server Error I'm going to end up in the onSuccess block. 如果出现500 Internal Server Error我将结束于onSuccess块。 From my meager understanding of promises I guess this seems correct because I technically did get a response? 从我对承诺的微不足道的理解中,我猜这似乎是正确的,因为我从技术上确实得到了回应? The problem is an onSuccess block seems like the wrong place to have a bunch of 问题是onSuccess块似乎是错误的地方,有一堆

if(res.status >= 400) {
  return $q.reject('something went wrong: ' + res.status);
}

Just so that my onReject block will get run. 只是为了让我的onReject块能够运行。 Is this the way it's supposed to work? 这是应该工作的方式吗? Do most people handle 400+ statuses in the onSuccess block or do they return a rejected promise to force the onReject block? 大多数人是在onSuccess块中处理400多个状态,还是返回被拒绝的承诺来强制onReject块? Am I missing a better way to handle this? 我是否缺少更好的方法来解决此问题?

I tried doing this in an httpInterceptor but I couldn't find a way to return a rejected promise from here. 我尝试在httpInterceptor执行此操作,但找不到从此处返回被拒绝的诺言的方法。

this.responseError = function(res) {
  if(res.status >= 400) {
    // do something
  }

  return res;
};

Your success-block will not be hit. 您的成功障碍将不会受到打击。 Try this and see that error-block will hit if error code > 300. 尝试此操作,如果错误代码> 300,则会看到错误块。

$http.get('/users').success(function(data, status, headers, config) {
    // this callback will be called asynchronously
    // when the response is available
  }).error(function(data, status, headers, config) {
    // called asynchronously if an error occurs
    // or server returns response with an error status.
  });

You could handle these in an interceptor instead of in your callback. 您可以在拦截器中处理这些,而不是在回调中处理。

In your app.config you can configure your $httpProvider to something like this: 在您的app.config中,您可以将$ httpProvider配置为如下所示:

$httpProvider.interceptors.push(['$q', function ($q) {
    return {
        request: function (config) {
            //do something 
            return config;
        },
        responseError: function (response) {
            if (response.status === 401) {
                //handle 401
            }
            return $q.reject(response);
        }
    };
}]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM