使用AngularJS使用REST服务

时间:2014-04-09 13:11:34

标签: angularjs

我有一个用Java编写的REST服务,它以JSON方式返回一个数据数组:

[{"key":"London","value":"51.30"}]

现在,我正在尝试使用AJS文档编写AngularJS REST客户端代码。到目前为止,我已经能够调用REST服务(我可以从服务器日志中看到),但HTML页面中没有打印任何内容。 这是我的代码:

<!doctype html>
<html  >
  <head>
     <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js"></script>
     <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular-resource.js"></script>
         <script language="javascript">


      angular.module('myApp',['ngResource']);
            function Ctrl($scope,$resource) {
              var Geonames = $resource(
              'http://localhost:8080/rest-application/rest/json', {     
               }, {
               query: { method: 'GET', isArray: true },
               create: { method: 'POST' }
            }
          );
          $scope.objs = Geonames.query();
         };
         Ctrl.$inject = ['$scope','$resource'];

  </script>
 </head>

    <body >
       <div ng-app="myApp">
              <div ng-controller="Ctrl">
                 {{objs.key}} - {{objs.value}}

              </div>
           </div>
    </body>
</html>

我尝试过这个例子,其中有几个小变体取自教程,但它仍然无效。有帮助吗?
谢谢!

2 个答案:

答案 0 :(得分:1)

您从query()获得的是一个数组,因此您应该使用ng-repeat

来循环它
 <div ng-app="myApp">
    <div ng-controller="Ctrl">
       <ul>
           <li ng-repeat="obj in objs">{{obj.key}} - {{obj.value}}</li>
       </ul>
    </div>
 </div>

答案 1 :(得分:1)

首先,让我们稍微整理一下你的代码:

var app = angular.module('myApp',['ngResource']);
// Controllers get their dependencies injected, as long as you don't minify your code and lose variable names.
app.controller('Ctrl', function($scope, $resource) {
    $scope.objs = []; // We initialize the variable for the view not to break.
    // For the query example, you don't need to define the method explicitly, it is already defined for you.
    var Geonames = $resource('http://localhost:8080/rest-application/rest/json');
    // Resource methods use promises, read more about them here: http://docs.angularjs.org/api/ng/service/$q
    Geonames.query({}, function(arrayResult) {
        $scope.objs = arrayResult;
    });
});

您必须使用ng-repeat指令调整html代码以处理数组中的每个项目:

<body>
    <div ng-app="myApp">
        <div ng-controller="Ctrl">
            <!-- object is a reference for each item in the $scope.objs array-->
            <span ng-repeat="object in objs">
                {{object.key}} - {{object.value}}
            </span>
        </div>
    </div>
</body>