从 rest 调用中捕获 errors/read 状态码 - angular

catch errors/read status code from rest call - angular

当以其中一种格式进行休息调用时,您如何捕获 errors/read http 状态代码,两者都可以 return 成功响应,只是不知道如何获取我需要的信息.我可以根据需要获取具有值 returned 的对象,我只是无法获取 http 状态代码。

@Claies 在回答这个问题时提供的方法()

$scope.makeRestCall= function () {
    $scope.member = Item.makeRestCallWithHeaders('123456789', '789456123')
    .query().$promise.then(function(response){

    });
};


 $scope.makeRestCall= function () {
    $scope.member = Item.makeRestCallWithHeaders('123456789', '789456123')
    .query({}, function() {

    })
};

我尝试在这里使用第一种方法并从 function(response) 中获取一些东西,例如 response.status,但它 return 未定义。

作为参考,使用这个工厂:

.factory("Item", function($resource) {
    var endpoint = "http://some valid url";

    function makeRestCallWithHeaders(id1, id2) {
        return $resource(endpoint, null, {
            query: {
                method: 'GET',
                headers: {
                    'id1': id1,
                    'id2': id2
                }
            }
        })
    }

    var item = {
        makeRestCallWithHeaders: makeRestCallWithHeaders
    }

    return item ;
})

项目 return 是这样的:

{firstName:Joe, lastName:smith}

我真的只是想弄清楚如何访问由 REST 调用 return 编辑的状态代码。绝对的最终目标是读取任何错误响应,并将 return 错误写入 angular 中的 UI。如果有一种方法可以在 UI 中阅读这篇文章,那也可以。

要读取错误状态,您需要传入 errorCallback to the $promise:

$scope.makeRestCall= function () {
$scope.member = Item.makeRestCallWithHeaders('123456789', '789456123')
    .query().$promise.then(
        function(response){
            //this is the successCallback
            //response.status & response.statusText do not exist here by default 
            //because you don't really need them - the call succeeded
            //see rest of answer below if you really need to do this
            //    but be sure you really do...
        },
        function(repsonse) {
            //this is the errorCallback
            //response.status === code
            //response.statusText === status text!
            //so to get the status code you could do this:
            var statusCode = response.status;
        }
    );
};

您不需要 successCallback 中的状态,因为它是成功的并且您隐含地知道成功代码。

因此默认情况下,状态在 successCallback 中不可用。

如果出于某种原因,您确实需要 successCallback 中的状态,您可以编写一个 interceptor 将此信息放在某个地方,但请注意 angular 框架处理数据在不同的成功场景中会有所不同,因此您需要针对不同的情况编写代码。