【问题标题】:$http.get method in angularjs for rest Apiangularjs中用于rest Api的$http.get方法
【发布时间】:2015-07-07 10:45:20
【问题描述】:

我想使用 angularjs 中的 $http.get 方法将 REST-API 的朋友列表获取到表中。请参阅DEMO。 当我单击按钮时,我无法加载 JSON 数据。

JSON.data

{
    "friends": [
        {
            "FirstName": "John",
            "LastName": "Doe"
        },
        {
            "FirstName": "Ann",
            "LastName": "Wellington"
        },
        {
            "FirstName": "Sabrina",
            "LastName": "Burke"
        }
    ]
}

索引.html

   <body ng-app="step4App">
        <div ng-controller="FriendsCtrl">
             <button ng-click="loadFriends()">Load Friends</button>
             <table>
                  <thead>
                     <tr><th>First</th><th>Last</th></tr>
                  </thead>
                  <tbody>
                     <tr ng-repeat="friend in friends">
                          <td>{{friend.FirstName}}</td>
                          <td>{{friend.LastName}}</td>
                     </tr>
                  </tbody>
             </table>

        </div>
        <script>
             var app=angular.module("step4App",[]);
             app.controller("FriendsCtrl", function($scope, $http){
                 $scope.loadFriends=function(){
                     $http.get("friendsList.json").success(function(data){
                          $scope.friends=data;
                     }).error(function(){
                          alert("An unexpected error occured!");
                     });
                 }
             });
        </script>
   </body>

【问题讨论】:

  • 您是否从 Apache 提供此服务?还是本地文件系统?如果您使用的是 Chrome,本地文件系统可能不适合您。

标签: json angularjs rest


【解决方案1】:

您的 JSON 文件有一个对象,而 $scope.friends 是一个数组。

你需要改变这个:

$scope.friends=data;

到:

$scope.friends = data.friends;

DEMO

【讨论】:

  • 感谢您的回复。它的工作原理,当这种情况出现时,我总是很困惑,你能解释一下吗.......
  • “更多”是什么意思?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-09-28
  • 1970-01-01
  • 1970-01-01
  • 2015-11-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多