简体   繁体   中英

$http/$q/promise Questions (in Angular)

I can't seem to wrap my head around when $q/$http should trigger the onReject block.

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. 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

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

Just so that my onReject block will get run. 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? 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.

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.

$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:

$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);
        }
    };
}]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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