Sunday, September 24, 2017

Cannot retrieve data from backend to html using AngularJS and Spring MVC

I was trying a bunch of data in html by using Java Spring MVC, angularjs, and hibernate. But I have faced some problem which is the data cannot display on designated page but on specific URL. Here attached my source code:

author-service.js

    'use strict';
angular.module('my_service_app').factory('AuthorService', ['$http', '$q', function($http, $q){
    console.log('TEST ANGULAR SERVICE 1');
    var REST_SERVICE_URI = 'http://localhost:8081/assignment_bookstore/author-moderator/'

    return {
            findAllAuthor: function () {
                console.log("TEST ANGULAR SERVICE S");
                return $http.get(REST_SERVICE_URI)
                        .then(
                                function(response){
                                    console.log("TEST 0: FINDALL");
                                    return response.data;
                                },
                                function(errResponse){
                                    console.error('Error while fetching authors');
                                    return $q.reject(errResponse);
                                }
                        );

}
}

}]);

author-route.js

'use strict';
(function()
{
    angular
    .module('my_route_app')
    .config(['$urlRouterProvider','$stateProvider',function($urlRouterProvider,$stateProvider) {
        $urlRouterProvider.otherwise('/');
        $stateProvider
            .state('author-moderator', {
                templateUrl: '/app/js/html/author.html',
                controller: "AuthorController as authorCtrl",
                url: '/author-moderator/',
                views:{
                    'header':{tempalteUrl: "app/js/html/header.html"},
                    'footer':{tempalteUrl: "app/js/html/footer.html"},
                    'content':{templateUrl: "app/js/html/author.html"}
                }
            })
    }]);

author-controller.js

'use strict';
console.log('TEST ANGULAR CTRL 1');
angular
.module('my_app')
.controller('AuthorController', ['$scope', 'AuthorService', function($scope, AuthorService) {
          var self = this;
          self.author={authorId:0,authorName:'',emailAddress:'',country:''};
          self.authors=[];

          console.log('TEST ANGULAR CTRL 2');
          self.findAllAuthor = function(){
              AuthorService.findAllAuthor()
                  .then(
                               function(d) {
                                    self.authors = d;
                               },
                                function(errResponse){
                                    console.error('Error while fetching authors');
                                }
                       );
              console.log('TEST ANGULAR CTRL 2.5');
          };

          function submit() {
              if(self.author.authorId===null){
                  console.log('Saving New Author', self.author);
                  addAuthor(self.author);
              }else{
                  updateAuthor(self.author, self.author.authorId);
                  console.log('User updated with id ', self.author.authorId);
              }
              reset();
          }

          self.reset = function(){
              self.author={authorId:null,authorName:'',emailAddress:'',country:''};
              $scope.formAuthor.$setPristine(); //reset Form
          };


      }


]);

AuthorController.java

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.util.UriComponentsBuilder;

import org.pacman.domain.entity.AuthorBean;
import org.pacman.service.AuthorService;

@RestController
//@RequestMapping(value="/#")
public class AuthorController {

        @Autowired
        AuthorService authorService;

        // Retrieve all author
        @RequestMapping(value = "/author-moderator/", method = RequestMethod.GET)
        public ResponseEntity<List<AuthorBean>> listAllAuthor(){
            System.out.println("TEST 1");
            List <AuthorBean> authors = authorService.findAllAuthor();
            System.out.println("TEST 2");
            if(authors.isEmpty()){
                System.out.println("TEST 3");
                return new ResponseEntity<List<AuthorBean>>(HttpStatus.NO_CONTENT);
            }
            return new ResponseEntity<List <AuthorBean>>(authors, HttpStatus.OK);
        }

        //Retrieve particular author
        @RequestMapping(value = "/author-moderator/{authorId}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
        public ResponseEntity<AuthorBean> getUser(@PathVariable("authorId") Integer authorId){
            System.out.println("Fetching author with authorId" + authorId);
            AuthorBean author = authorService.getAuthorById(authorId);
            if(author == null){
                System.out.println("author with authorId " + authorId + " not found");
                return new ResponseEntity<AuthorBean>(HttpStatus.NOT_FOUND);
            }
            return new ResponseEntity<AuthorBean>(HttpStatus.OK);

        }

        //Create author
        @RequestMapping(value = "/author-moderator/", method = RequestMethod.POST)
        public ResponseEntity<Void> addAuthor(@RequestBody AuthorBean author, UriComponentsBuilder ucBuilder) {
            System.out.println("Creating Author " + author.getAuthorName());

            authorService.addAuthor(author);

            HttpHeaders headers = new HttpHeaders();
            headers.setLocation(ucBuilder.path("/author-moderator/{authorId}/").buildAndExpand(author.getAuthorId()).toUri());
            return new ResponseEntity<Void>(headers, HttpStatus.CREATED);
        }

        //Update author
        @RequestMapping(value = "/author-moderator/{authorId}", method = RequestMethod.PUT)
        public ResponseEntity<AuthorBean> updateUser(@PathVariable("authorId") Integer authorId, @RequestBody AuthorBean author){
            System.out.println("Updateing author " + authorId);
            AuthorBean currentAuthor = authorService.getAuthorById(authorId);
            if(currentAuthor == null){
                System.out.println("author with id " + authorId + " not found");
                return new ResponseEntity<AuthorBean>(currentAuthor, HttpStatus.NOT_FOUND);
            }
            currentAuthor.setAuthorName(author.getAuthorName());
            currentAuthor.setAuthorEmailAddress(author.getAuthorEmailAddress());
            currentAuthor.setCountry(author.getCountry());

            authorService.updateAuthor(currentAuthor);
            return new ResponseEntity<AuthorBean>(currentAuthor, HttpStatus.OK);
        }

        //Delete author
        @RequestMapping(value = "/author-moderator/{authorId}", method = RequestMethod.DELETE)
        public ResponseEntity<AuthorBean> deleteAuthor(@PathVariable("authorId") Integer id) {
            System.out.println("Fetching & Deleting User with id " + id);

            AuthorBean author = authorService.getAuthorById(id);
            if (author == null) {
                System.out.println("Unable to delete. User with id " + id + " not found");
                return new ResponseEntity<AuthorBean>(HttpStatus.NOT_FOUND);
            }

            authorService.deleteAuthorById(id);
            return new ResponseEntity<AuthorBean>(HttpStatus.NO_CONTENT);
        }

}

author.html

<h1>Author</h1>
<div ng-controller="AuthorController as ctrl">

    <form name="formAuthor" ng-submit="ctrl.submit()" method="post">
        <table>
            <!-- <input type="hidden" ng-model="ctrl.author.authorId"> -->
            <tr>
                <td>Author ID</td>
                <td>: <input type="number" ng-model="ctrl.author.authorId"></td>
            </tr>
            <tr>
                <td>Author Name</td>
                <td>: <input type="text" ng-model="ctrl.author.authorName"></td>
            </tr>
            <tr>
                <td>Author Email</td>
                <td>: <input type="text" ng-model="ctrl.author.emailAddress"></td>
            </tr>
            <tr>
                <td>Author Country</td>
                <td>: <input type="text" ng-model="ctrl.author.country"></td>
            </tr>
            <tr>
                <td colspan="2" align="center">
                        <input type="submit" ng-click="ctrl.addAuthor(author)" value="Add Author">
                        <input type="button" ng-click="ctrl.reset()" value="Reset">
                </td>
            </tr>
        </table>
    </form>
<!--  -->
<div class="tablecontainer">
            <table class="table table-hover">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>Name</th>
                        <th>Email</th>
                        <th>Country</th>
                    </tr>
                </thead>
                <tbody>
                    <tr ng-repeat="a in ctrl.authors">
                        <td><span ng-bind="a.authorId"></span></td>
                        <td><span ng-bind="a.authorName"></span></td>
                        <td><span ng-bind="a.emailAddress"></span></td>
                        <td><span ng-bind="a.country"></span></td>
                    </tr>
                </tbody>
            </table>
        </div>
        <div>
        </div>
</div>

index.jsp

<!DOCTYPE html>
<%@ page language="java" contentType="text/html"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<html lang="en" ng-app="my_app">

  <head>
  <title>Bookstore Management</title>
    <link href="<c:url value='/app/css/bootstrap.css' />" rel="stylesheet"></link>
    <link href="<c:url value='/app/css/app.css'/>" rel="stylesheet"></link>
  </head>
<body>
<div class="container">
    <div class="page-header">
    <h2>iSlow Bookstore</h2>
    <small>Spring Assignment</small>
    </div>
</div>
    <div class="generic-container">
        <button><a ui-sref="author-moderator">Author Moderator</a></button>
    </div>
        <!-- header -->
        <div ui-view="header"></div>

        <!-- main -->
        <div ui-view="content"></div>

        <!-- footer -->
        <div ui-view="footer"></div>
        <script src="<c:url value='/webjars/angularjs/1.4.8/angular.js' />"></script>
        <script src="<c:url value='/webjars/angular-ui-router/0.2.18/angular-ui-router.js' />"></script>
        <script src="<c:url value='/webjars/angularjs/1.4.8/angular-route.js' />"></script>
        <script src="<c:url value='/webjars/jquery/2.0.3/jquery.min.js' />"></script>

    <!-- Temporary store route -->
    <script src="<c:url value='/app/js/app.js' />"></script>

    <script src="<c:url value='/app/js/app-route.js' />"></script>
    <script src="<c:url value='/app/js/app-service.js' />"></script>

    <!-- route -->
    <script src="<c:url value='/app/js/route/author-route.js' />"></script>

    <!-- service -->
    <script src="<c:url value='/app/js/service/author-service.js' />"></script>

    <!-- controller -->
    <script src="<c:url value='/app/js/controller/author-controller.js' />"></script>

</body>

</html>

When I try to access http://localhost:8081/assignment_bookstore/#/author-moderator/ it display nothing in table, but if I access http://localhost:8081/assignment_bookstore/author-moderator/ I can retrieve the data in json format. Is it about URL Mapping issue? Please help me.

Source: AngularJS



from Angular Questions https://angularquestions.com/2017/09/25/cannot-retrieve-data-from-backend-to-html-using-angularjs-and-spring-mvc/
via @lzomedia #developer #freelance #web

No comments:

Post a Comment