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":"[email protected]","phone":"90908989899"}]

1

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.