【问题标题】:How to call restful services from angularjs如何从angularjs调用restful服务
【发布时间】:2013-10-23 09:44:54
【问题描述】:

我在 java 中编写了一个 restful 服务并从 angularjs 调用它,但它不起作用。如果我把静态 json 格式它的作品。但不适用于 RESTful 服务。以下是我在服务文件中的代码。

angular.module('intelesant.services', [])
    .value('version', '0.1')
    .service('customers1',function(){
         return $resource('http://api.geonames.org/citiesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&lang=de&username=demo', {}, {
             query: { method: 'GET', isArray: true },
             create: { method: 'POST' }
     })
});

我的控制器文件是

intelesant.controller('HomeController', ['$scope','customers1', function(s,customers) {

    alert(JSON.stringify(customers));
    s.homeContent = 'Test Content for Home page. This can come from server via REST service.';
}]);

【问题讨论】:

    标签: java json angularjs


    【解决方案1】:

    有一个名为 Restangular 的 AngularJS 服务,您可以轻松地在应用程序中实现 RESTful 服务。

    这用最少的客户端代码简化了常见的 GET、DELETE 和 UPDATE 请求。它非常适合使用来自 RESTful API 的数据的任何 WebApp。

    更多详情请参考Restangular

    【讨论】:

      【解决方案2】:

      您是否在代码中注入 ngResource 并包含 angular-resource.min.js?这里是fiddle accessing your service

      angular.module('myApp', ['ngResource']);
      function Ctrl($scope,$resource) {
          var Geonames = $resource('http://api.geonames.org/citiesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&lang=de&username=demo', 
              {   }, 
              {
                query: { method: 'GET', isArray: true },
                create: { method: 'POST' }
              }
           );
           $scope.objs = Geonames.query();
         };
      };
      Ctrl.$inject = ['$scope','$resource'];
      

      【讨论】:

      • 抱歉,stackoverflow 代码的东西不喜欢我的粘贴,但请看小提琴。由于使用演示帐户的多次访问,我在运行时遇到错误,但它似乎工作正常。
      猜你喜欢
      • 2015-06-14
      • 1970-01-01
      • 1970-01-01
      • 2011-08-28
      • 2011-08-28
      • 2014-03-22
      • 2011-11-02
      • 2015-12-15
      • 1970-01-01
      相关资源
      最近更新 更多