How do I get the HTTP response status code in Angu

2019-01-13 15:59发布

Using ngResource in AngularJS 1.2rc(x), how do I get the status code now?

RestAPI.save({resource}, {data}, function( response, responseHeaders ) {
});

where RestAPI is my ngResource.

The response has the $promise object and the resource returned from the server but not a status anymore. The responseHeaders() function only has a status if the server injects the status code into the header object, but not the true returned status code. So some servers may serve it and some might not.

8条回答
够拽才男人
2楼-- · 2019-01-13 16:30

For anyone using a newer version of Angular, looks like we've had access to the status code as a 3rd param to the transformResponse function since angular 1.3, but it was never documented properly in the $resource docs.

查看更多
\"骚年 ilove
3楼-- · 2019-01-13 16:31

I'm using AngularJS v1.5.6, and I do it like this (in my case I put the "getData" method inside a service):

function getData(url) {
    return $q(function (resolve, reject) {
        $http.get(url).then(success, error);

        function success(response) {
            resolve(response);
        }
        function error(err) {
            reject(err);
        }
    });
}

then in the controller (for example), call that like this:

function sendGetRequest() {
    var promise = service.getData("someUrlGetService");
    promise.then(function(response) {
        //do something with the response data
        console.log(response.data);
    }, function(response) {
        //do something with the error
        console.log('Error status: ' + response.status);
    });
}

As documentation says, the response object has these properties:

  • data – {string|Object} – The response body transformed with the transform functions.
  • status – {number} – HTTP status code of the response.
  • headers – {function([headerName])} – Header getter function.
  • config – {Object} – The configuration object that was used to generate the request.
  • statusText – {string} – HTTP status text of the response.

See https://docs.angularjs.org/api/ng/service/$http

Hope it helps!

查看更多
登录 后发表回答