java - 如何在 angularjs 中使用 $resource 来使用 Spring Restful Web 服务

标签 java angularjs spring hibernate rest

我正在使用 angularjs 开发一个 Spring Restful 应用程序。在 Spring 中,我使用 Maven 和 Hibernate。

我已经使用 spring Rest 返回了 json 对象,但我不知道如何使用 $resource 在我的 Angular Controller 中使用这个对象

这是我的 Spring 休息 Controller

@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 Controller 代码

我的应用程序名称是:SpringRestCrud1

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

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

最佳答案

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
      }
    });
  });

从那里您可以设置 Controller 来访问列表:

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

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

    });

以及显示员工列表的 View :

<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.

关于java - 如何在 angularjs 中使用 $resource 来使用 Spring Restful Web 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31130583/

相关文章:

java - Spring在配置中指定实现

java - 什么是出境饱和情况?在netty中如何处理?

java - 如何在 java 中将 HexString 转换为 jpg 图像?

angularjs - 请求不显示带有正文解析器的数据

javascript - angularjs: ngModel controller $parser & $formatter 在元素被移除后仍然触发

java - @IfProfileValue 从环境变量导入集,测试未执行

java - 速度 - 更正正则表达式以删除控制字符?

java - 无法更新/替换 MySql 中的多个存储图像

javascript - Angular .js : directive object in scope is always undefined

java - Spring:我可以为模型属性定义标签吗?