0

I am developing a spring restful application with angularjs. In Spring i am using maven and Hibernate.

I have returned json object using spring rest but i dont know how to use this object in my angular controller using $resource

Here is my spring rest 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;
}

Here is my jsp

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

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

<h3>LastName:</h3>

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

So please help me with angularjs controller code

My application name is: SpringRestCrud1

My path which is used to return the json object is: http://localhost:8080/SpringRestCrud1/employee/list

And my result is: [{"id":3,"firstName":"Hoston","lastName":"lindey","email":"hl@gmail.com","phone":"90908989899"}]

Nadeem Ahmed
  • 371
  • 2
  • 8
  • 24

1 Answers1

1

ngResource is very simple to use. How I typically use it is I first create a factory that is used to map to the CRUD endpoint:

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

From there you can set up a controller to access the list:

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

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

    });

And a view to show the employee list:

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

I would suggest though that you redesign your endpoints to be more RESTful if you are going to use ngResource. Here's a good guide for that.

Daniel Cottone
  • 4,257
  • 24
  • 39