如果在AngularJS中找不到记录,则使用http.get生成错误消息

时间:2016-08-19 12:35:56

标签: javascript angularjs xmlhttprequest

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

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

3 个答案:

答案 0 :(得分:0)

如果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
});

答案 1 :(得分:0)

这很简单,你可以检查你是否回复.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
        }
     });

答案 2 :(得分:0)

派生的承诺由返回投掷创建到处理程序函数。

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方法。