How do I get the HTTP response status code in AngularJS 1.2

前端 未结 8 1817
半阙折子戏
半阙折子戏 2020-12-05 03:04

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

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


        
8条回答
  •  爱一瞬间的悲伤
    2020-12-05 03:23

    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!

提交回复
热议问题