【问题标题】:Produce error message with http.get if a record isn't found in AngularJS如果在 AngularJS 中找不到记录,则使用 http.get 生成错误消息
【发布时间】:2016-08-20 05:52:55
【问题描述】:

我将订单数据输入我的应用程序并填充我的字段,但如果我输入了错误的订单号,它不会引发错误,只会用空白信息填充字段。

$http.get('http://example.com/api' + query).success(function(data) {
    $scope.orders = data;
    console.log($scope.query);
    console.log(data);
    console.log($scope.orders);

有很多示例,但没有完全可用的代码,任何人都可以帮助编译一个 http.get 函数,如果订单不匹配,该函数将产生错误并显示“未找到订单”错误。

$http.get('http://example.com').then(function(response){
    //the response from the server is now contained in 'response'
}, function(error) {
    //there was an error fetching from the server
});

【问题讨论】:

  • 我相信你应该处理这个服务器端,因为它是一个逻辑错误,你目前得到的是空值,成功响应为 200(因此不会引发错误)。否则,您应该检查收到的响应中的数据,如果为空,请通知您的用户或一般做一些事情。
  • 您需要处理query 变量并使用if 进行测试,如果一切正常。否则你可能只想在你的后端抛出一个错误然后你可以使用function(error){}
  • 谢谢 mkaran。事实上,一个空订单在 Postman 中返回 200 OK 但有一个空的:data {} 所以也许得到这个排序的服务器端是要走的路,否则一个基于“结果”[[{“原因”:“无效订单”的函数,“动作”:“getOrder”,“数据”:{},“结果”:“失败”}]```

标签: javascript angularjs xmlhttprequest


【解决方案1】:

如果 API 返回带有 status - 200 OK 的空结果,则表示按照以下代码抛出错误,或者要求服务器团队抛出 404 状态代码以在您的 API 本身上找不到匹配项。

$http.get('http://example.com').then(function(response){
    if(response.data==''){
        //Throw error message as 'Order not found'
    }
    //the response from the server is now contained in 'response'
}, function(error){
    if(error.status=='404'){
        //Throw error message as 'Order not found'
    }
    //there was an error fetching from the server
});

【讨论】:

    【解决方案2】:

    很简单,你可以检查你的response.data有没有。

    下面是相同的代码...

     $http.get('http://example.com').then(function(response){
                if(!response.data){
                   // here you can throw error message 'Order not foun
                }
         }, function(error){
             //there was an error fetching from the server
            }
         });
    

    【讨论】:

      【解决方案3】:

      派生的承诺是通过返回抛出到处理函数来创建的。

      var httpPromise = $http.get('http://example.com');
      
      var derivedPromise = httpPromise.then( function onSuccess(response) {
           if (response.data.length == 0) {
               response.status = 404;
               response.statusText = "Not Found -- Zero records";
               //throw to chain rejection
               throw response;
           } else {
               //return to chain response
               return response;
           };
      });
      

      上述示例零长度数据的响应转换为拒绝。

      注意.sucesss 方法忽略 返回(或抛出)值。 .sucesss.error 方法不适合链接,已被弃用。

      弃用通知1

      $http 旧承诺方法 .success.error 已被弃用。请改用标准的.then 方法。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-01-16
        • 2015-03-14
        • 1970-01-01
        • 2013-12-06
        • 1970-01-01
        • 2013-04-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多