在 angular $http 服务中,我如何捕捉“状态"?错误? [英] In angular $http service, How can I catch the "status" of error?

查看:20
本文介绍了在 angular $http 服务中,我如何捕捉“状态"?错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读一本名为Pro Angular JS"的书.但是,我有一个关于如何捕获错误状态的问题.

I'm reading a book called, "Pro Angular JS". However, I have a question about how to catch a status of error.

我编码的是:

$http.get(dataUrl)
    .success(function (data){
        $scope.data.products = data;
    })
    .error(function (error){
        $scope.data.error=error;
        console.log($scope.data.error.status); // Undefined!
        // (This is the spot that I don't get it.)                                         
    });

如果我编码console.log($scope.data.error.status);",为什么console.log的参数是undefined?

If I code "console.log($scope.data.error.status);" , why does the argument of console.log is undefined?

书中有一句话,传递给错误函数的对象定义了状态和消息属性."

In the book, there are sentence, "The object passed to the error function defines status and message properties."

所以我做了 $scope.data.error.status

So I did $scope.data.error.status

为什么会出错?

推荐答案

您的参数不正确,错误没有返回包含状态和消息的对象,而是按照下面描述的顺序将它们作为单独的参数传递.

Your arguments are incorrect, error doesn't return an object containing status and message, it passed them as separate parameters in the order described below.

取自 angular 文档:

  • data – {string|Object} – 使用转换函数转换的响应主体.
  • status – {number} – 响应的 HTTP 状态代码.
  • headers – {function([headerName])} – 头部获取函数.
  • config – {Object} – 用于生成请求的配置对象.
  • statusText – {string} – 响应的 HTTP 状态文本.

因此您需要将代码更改为:

So you'd need to change your code to:

$http.get(dataUrl)
    .success(function (data){
        $scope.data.products = data;
    })
    .error(function (error, status){
        $scope.data.error = { message: error, status: status};
        console.log($scope.data.error.status); 
  }); 

显然,您不必创建表示错误的对象,您可以只创建单独的范围属性,但适用相同的原则.

Obviously, you don't have to create an object representing the error, you could just create separate scope properties but the same principle applies.

这篇关于在 angular $http 服务中,我如何捕捉“状态"?错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆