Search code examples
angularjsspring-restcontroller

Connecting Angularjs to Spring RESTFul service using AngularJS $http service


This is the Spring Rest controller in the back end which simply get all the student in the list. I have tested it and works fine.

@RestController
@RequestMapping("a/rest")
public class RestfulController {

    @Autowired
    private StudentDao studentDao;
    @RequestMapping(method = RequestMethod.GET)
    public ResponseEntity<List<Student>> index() {
        ResponseEntity<List<Student>> studList = new ResponseEntity<List<Student>>( studentDao.getAll(), HttpStatus.OK);
        return studList;
    }
}

This is what i am trying to do i want that list of student to display in the paragraph with id defined(id="displayData")

I have created button that loads the function showData()

Then i am trying to implement $http service of Angularjs for connecting to the back in this way

<body>

<input type="button" value="Get Data" onclick="showData()" />
<p id="displayData" />

</body>

<script type="text/javascript">

function showData() {
$http({
  method: 'GET',
  url: 'a/rest'
}).then(function (response) {

    $('#displayData').html(JSON.stringify(response));

  });

}
</script>

Here i need help..!! Problem is on the frontend. How can i implement $http service that works file?


Solution

  • $http response will contain

    $http response json

    properties. $http response.data contain actual json data. It does not work the way jquery($.ajax()) work. You need to bootstrap your angular application before you can use $http service.

    Below is minimal example suit to your need.

    <!DOCTYPE html>
    <html>
    <head>
        <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
    </head>
    <body ng-app="studApp" ng-controller="StudController">
    
        <input type="button" value="Get Data" ng-click="showData()" />
        <p id="displayData" />
    
        <script type="text/javascript">
            angular.module('studApp', [])
            .controller('StudController', function($http, $scope) {
              $scope.showData = function() {
                $http({
                  method : 'GET',
                  url : 'a/rest'
                }).then(function(response) {
                  $('#displayData').html(JSON.stringify(response.data));
                });
              }
            });
        </script>
    </body>
    </html>