如何在表中显示$ http错误状态?

时间:2019-03-26 10:09:27

标签: angularjs

在尝试从服务器循环遍历对象数组以显示某些数据时如何显示错误状态,但是$ http请求以某种方式遇到某些错误?我试图修改此在线找到的代码,但是如果更改服务器名称,似乎无法显示错误。

<body>    
    <div ng-app="myApp" ng-controller="customersCtrl">         
        <ul>            
            <li ng-repeat="x in myData">
            enter code here`{{ x.Name + ', ' + x.Country }}
            </li>            
        </ul>        
    </div>        
    <script>        
        var app = angular.module('myApp', []);
        app.controller('customersCtrl', function($scope, $http) {            
            $http.get("customers.php").then(function (response) {
            $scope.myData = response.data.records;
            });            
        });        
    </script>    
</body>

在这里,如果我将服务器名称更改为不正确的名称,则无法打印错误状态。

1 个答案:

答案 0 :(得分:0)

从角度文档

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

所以就您而言

<script>
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
$http.get("customers.php").then(function (response) {
$scope.myData = response.data.records;
},
function errorCallback(response) {
    //do something with error
      })

);
</script>