Angular http get with REST



我正在使用 Rest 在我的本地 localhost 上以 Json 格式显示数据库中的信息。网址 http://localhost:8080/restful-services/api/getAllHorses。

我是 Angular 的新手,我想做的是使用 http get 来访问 json 信息。

这是我的json

[{"horse":{"age":"6yo","breeder":"David Harvey","countryBred":"(IRE)","horseAge":"6yo","horseId":1,"horseName":"Brain Power","owner":"Michael Buckley","pedigree":"Kalanisi","sex":"(08May11 b g)","trainer":{"days":9,"location":"Lambourn","seaonWinners":119,"seasonStrikeRate":27,"stake":-69.77,"trainerId":2,"trainerName":"Nicky Henderson"},"trainerName":"Nicky Henderson"}},

这是我在 Angular 上尝试过的,但它没有显示任何内容。非常感谢任何帮助,谢谢。

var horseApp = angular.module('horseApp', []);
   horseApp.controller('HorseCtrl', function ($scope, $http){
      $http.get('http://localhost:8080/restful-services/api/getAllHorses').success(function(data) {
      $scope.horse = data;
   });
});
<body ng-controller="HorseCtrl">
   <h2>Horses</h2>
   <table>
      <tr>
         <th>Age</th>
         <th>Name</th>
         <th>Breeder</th>
      </tr>
      <tr ng-repeat="age in Horse.age ">
         <td>{{horse.age}}</td>
         <td>{{horse.horesName}}</td>
         <td>{{horse.breeder}}</td>
      </tr>
   </table>
</body>
  • $http.success已过时,请改用then。见$http
  • 你想迭代你的数组,所以修改 ng-repeat 应该这样做,现在你指向一个属性年龄,这是无效的horse因为它是一个数组。horse更好的名称是 horses .

修改后的代码

  horseApp.controller('HorseCtrl', function ($scope, $http){
    $http.get('http://localhost:8080/restful-services/api/getAllHorses')
        .then(function(response) {
      $scope.horse = response.data;
    });
  });

目录

<tr ng-repeat="item in horse">
    <td>{{item.age}}</td>
    <td>{{item.horesName}}</td>
    <td>{{item.breeder}}</td>
</tr>

更改 ng-repeat 中的变量,如下所示

<tr ng-repeat="h in horses">
    <td>{{h.horse.age}}</td>
    <td>{{h.horse.horesName}}</td>
    <td>{{h.horse.breeder}}</td>
</tr>

使用then而不是success

 $http.get('http://localhost:8080/restful-services/api/getAllHorses')
  .then(function(response) {
        $scope.horses = data;
  });

最新更新