【问题标题】:how to consume spring restful web service using $resource in angularjs如何使用 angularjs 中的 $resource 使用 Spring RESTful Web 服务
【发布时间】:2015-09-16 19:06:21
【问题描述】:

我正在使用 angularjs 开发一个 spring restful 应用程序。在 Spring 中,我使用 maven 和 Hibernate。

我已经使用 spring rest 返回了 json 对象,但我不知道如何使用 $resource 在我的角度控制器中使用这个对象

这是我的弹簧休息控制器

@RequestMapping(value = "/list", method = RequestMethod.GET)
public @ResponseBody
List<Employee> getEmployee() {
List<Employee> employeeList = null;
    try {
employeeList = dataServices.getEntityList();

    } catch (Exception e) {
        e.printStackTrace();
    }

    return employeeList;
}

这是我的jsp

<body>
<h3>FirstName:</h3>

<!-- First name from json object -->
<p></p>

<h3>LastName:</h3>

<!-- Last name from json object -->
<p></p>
</body>

所以请帮我处理 angularjs 控制器代码

我的应用名称是:SpringRestCrud1

我用来返回 json 对象的路径是:http://localhost:8080/SpringRestCrud1/employee/list

我的结果是:[{"id":3,"firstName":"Hoston","lastName":"lindey","email":"hl@gmail.com","phone":"90908989899 "}]

【问题讨论】:

标签: java angularjs spring hibernate rest


【解决方案1】:

ngResource 使用起来非常简单。我通常如何使用它是我首先创建一个用于映射到 CRUD 端点的工厂:

angular.module('angularRestCrud1')
  .factory('Employee', function ($resource) {
    return $resource('http://localhost:8080/SpringRestCrud1/employee/list', {}, {
      'query': {
        method: 'GET',
        params: { action: 'read', format: '.json' } , isArray : false
      }
    });
  });

您可以从那里设置一个控制器来访问列表:

angular.module('angularRestCrud1')
  .controller('EmployeeCtrl', function ($scope, Employee) {

    // Promise chain to resolve employee
    Employee.query(function (data) {
      $scope.employees = data;
    });

    });

还有一个显示员工列表的视图:

<body>
    <div ng-repeat="employee in employees track by $index">
        <h3>FirstName:</h3>
        <!-- First name from json object -->
        <p>{{ employee.firstName }}</p>

        <h3>LastName:</h3>
        <!-- Last name from json object -->
        <p>{{ employee.lastName }}</p>
    </div>  
</body>

如果你打算使用 ngResource,我建议你重新设计你的端点,使其更加 RESTful。 Here's a good guide for that.

【讨论】:

  • @NadeemAhmed 这回答了你的问题吗?
猜你喜欢
  • 2015-02-20
  • 1970-01-01
  • 1970-01-01
  • 2017-07-08
  • 2012-12-07
  • 2014-03-22
  • 2017-01-12
  • 1970-01-01
相关资源
最近更新 更多