【问题标题】:In angular $http service, How can I catch the "status" of error?在有角度的 $http 服务中,如何捕捉错误的“状态”?
【发布时间】:2015-02-14 22:39:26
【问题描述】:

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

我编码的是:

$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的参数是未定义的?

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

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

为什么会出错?

【问题讨论】:

  • 如果你只做console.log($scope.data.error);会传达什么信息?
  • @Clawish 然后,打印“未找到”。但是,我要打印的是“404”
  • 谢谢大家!!因为即使这是我在这个网站上的第一个问题,也有很多有用的答案,我很高兴!真是个好网站!!
  • 成功和错误已被弃用:stackoverflow.com/questions/35329384/…

标签: javascript angularjs


【解决方案1】:

响应状态作为回调中的第二个参数,(from docs):

// Simple GET request example :
$http.get('/someUrl').
  success(function(data, status, headers, config) {
    // this callback will be called asynchronously
    // when the response is available
  }).
  error(function(data, status, headers, config) {
    // called asynchronously if an error occurs
    // or server returns response with an error status.
  });

【讨论】:

    【解决方案2】:

    更新: 从 angularjs 1.5 开始,promise 方法成功和错误已被弃用。 (见this answer

    来自current docs

    $http.get('/someUrl', config).then(successCallback, errorCallback);
    $http.post('/someUrl', data, config).then(successCallback, errorCallback);
    

    你可以像这样使用函数的其他参数:

    error(function(data, status, headers, config) {
        console.log(data);
        console.log(status);
    }
    

    请参阅 $http 文档:

    // Simple GET request example :
    $http.get('/someUrl').
      success(function(data, status, headers, config) {
        // this callback will be called asynchronously
        // when the response is available
      }).
      error(function(data, status, headers, config) {
        // called asynchronously if an error occurs
        // or server returns response with an error status.
      });
    

    【讨论】:

    • 非常感谢!那么,书错了吗?在书中,“传递给错误函数的对象定义了状态和消息属性”。角度变了吗?
    • 我记得一样。确保您始终阅读文档,并且它们适用于您的角度版本。 (所有可用版本都有一个下拉菜单)
    【解决方案3】:

    来自官方angular documentation

    // Simple GET request example :
    $http.get('/someUrl').
      success(function(data, status, headers, config) {
        // this callback will be called asynchronously
        // when the response is available
      }).
      error(function(data, status, headers, config) {
        // called asynchronously if an error occurs
        // or server returns response with an error status.
      });
    

    如您所见,错误回调的第一个参数是数据,而状态是第二个。

    【讨论】:

    • 阅读这篇文章的人,来自 Angular 1.4,.success.error 已被弃用,取而代之的是 .then
    • 从 Angular 1.6 开始,.success.error 不再可用,你不得不使用 .then 和可能 .catch
    【解决方案4】:

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

    取自angular docs

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

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

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

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

    【讨论】:

    • 非常感谢!那么,书错了吗?在书中,“传递给错误函数的对象定义了状态和消息属性。”角度变了吗?
    • 我在更改日志中看不到任何表明这已更改的内容。
    • 从 Angular 1.4 开始,文档现在有一条弃用通知,说明“$http 旧式 promise 方法成功和错误已被弃用。请改用标准 then 方法。”
    • 重申@Darryl、.success.error 现在已弃用。请改用.then(function successCallback(response) {}, function errorCallback(response) {});
    • 自发布此答案以来,.success.error 已被弃用。
    【解决方案5】:

    由于$http.get 使用额外的便利方法successerror(仅包装then 的结果)返回一个“承诺”,您应该能够使用(无论您的Angular 版本如何):

    $http.get('/someUrl')
        .then(function success(response) {
            console.log('succeeded', response); // supposed to have: data, status, headers, config, statusText
        }, function error(response) {
            console.log('failed', response); // supposed to have: data, status, headers, config, statusText
        })
    

    严格来说不是问题的答案,但如果您被“我的 Angular 版本与文档不同”问题困扰,您可以随时转储所有 arguments,即使您不知道适当的方法签名:

    $http.get('/someUrl')
      .success(function(data, foo, bar) {
        console.log(arguments); // includes data, status, etc including unlisted ones if present
      })
      .error(function(baz, foo, bar, idontknow) {
        console.log(arguments); // includes data, status, etc including unlisted ones if present
      });
    

    然后,根据您找到的任何内容,您可以“修复”要匹配的函数参数。

    【讨论】:

      【解决方案6】:

      $http 旧承诺方法 successerror 已被弃用。请改用标准的then 方法。看看文档https://docs.angularjs.org/api/ng/service/$http

      现在正确的使用方法是:

      // Simple GET request example:
      $http({
        method: 'GET',
        url: '/someUrl'
      }).then(function successCallback(response) {
          // this callback will be called asynchronously
          // when the response is available
        }, function errorCallback(response) {
          // called asynchronously if an error occurs
          // or server returns response with an error status.
      });
      

      响应对象具有以下属性:

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

      200 到 299 之间的响应状态码被视为成功状态,将导致调用成功回调。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-05-31
        • 2020-04-02
        • 1970-01-01
        • 1970-01-01
        • 2020-05-30
        • 2019-10-09
        • 1970-01-01
        • 2018-09-08
        相关资源
        最近更新 更多