【问题标题】:catch errors/read status code from rest call - angular从休息调用中捕获错误/读取状态代码 - 角度
【发布时间】:2015-08-18 01:46:30
【问题描述】:

在以其中一种格式进行休息调用时,您如何捕获错误/读取 http 状态代码,两者都可以返回成功的响应,只是不知道如何获取我需要的信息。我可以根据需要获取返回值的对象,只是无法获取 http 状态码。

@Claies 在回答这个问题时提供的方法 (Get data from $resource response in angular factory)

$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,但它返回未定义。

参考,使用这个工厂:

.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 ;
})

项目返回如下内容:

{firstName:Joe, lastName:smith}

我真的只是想弄清楚如何访问 REST 调用返回的状态代码。绝对最终目标是读取任何错误响应并将错误返回到以角度编写的 UI。如果有一种方法可以在 UI 中读取它,那也可以。

【问题讨论】:

    标签: angularjs angular-promise angularjs-resource


    【解决方案1】:

    要读取错误状态需要传入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 将此信息放在某处,但请注意,角度框架在不同的成功场景中以不同方式处理数据,因此您将需要针对不同的情况编写代码。

    【讨论】:

    • 谢谢,在errorCallBack中,拦截器也是获取响应码/消息的解决方案吗?
    • 不,对于状态码,您可以简单地:“var statusCode = response.status;”我将编辑我的答案以使其更清晰!调用成功时只需要使用拦截器获取状态码/文本
    • 非常感谢您的澄清,非常感谢。
    猜你喜欢
    • 2019-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-02
    • 2013-01-29
    • 2020-06-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多