简体   繁体   English

实现AngularJS时未使用Spring-boot RESTful服务

[英]Spring-boot RESTful services not being used when implementing AngularJS

I set this all up by hand and when the application starts spring-boot displays the index.html page with has a AngularJS <div ng-view></div> my configuration files do work in my AngularJS project but now I am trying to get information back from my restful services and it appears they are no longer being called. 我手动进行了所有设置,当应用程序启动时,spring-boot会显示index.html页面,其中包含AngularJS <div ng-view></div>我的配置文件确实可以在我的AngularJS项目中正常工作。从我的安心服务中获取信息,似乎不再被调用。 Pretty much once it is passed to index.html, angular takes control. 一旦将其传递给index.html,就可以控制角度。

indexController.java indexController.java

@RestController
public class IndexController {

    @RequestMapping("/")
    public String index(){
        System.out.println("Looking in the index controller.........");
        return "index";
    }

}

FormRestController.java FormRestController.java

@RestController
public class FormRestController {

    @Autowired
    UserService userService;

    //-------------------Retrieve All Users--------------------------------------------------------

    @RequestMapping(value = "/getUsers", method = RequestMethod.GET)
    public ResponseEntity<List<User>> listAllUsers() {

        System.out.println("listAllUsers() is being called inside RestController............");

        List<User> users = userService.findAllUsers();
        if(users.isEmpty()){
            return new ResponseEntity<List<User>>(HttpStatus.NOT_FOUND);
        }
        return new ResponseEntity<List<User>>(users, HttpStatus.OK);
    }

users.config.js users.config.js

angular.module('myApp')
    .config(['$routeProvider', function ($routeProvider){

        $routeProvider.when('/users', {
            templateUrl: 'app/scripts/Customers/users.html',
            controller: 'UsersController'
        }).otherwise({redirectTo:'/'});

    }]);

usersService.js usersService.js

angular.module('myApp')
.factory('usersService',['$http', '$q', function($http,$q){

return {

    fetchAllUsers: function(){
        console.log("inside fetchAllUsers");
        return $http.get('/getUsers')
            .then(
                function(response){
                    return response;
                },
                function(errResponse){
                    console.error("Error while fetching customers"+errResponse);
                    return $q.reject(errResponse);
                }
            );
    }
}

}]); }]);

users.controller.js users.controller.js

angular.module('myApp')
.controller('UsersController', ['$scope', 'usersService', function($scope,    
usersService){

this.user = {id:null, username:'', address:'',email:''};
this.users = [];

var self = this;

this.fetchAllUsers = function(){
    var usersSelf = self;

    usersService.fetchAllUsers()
        .then(
            function(d){
                usersSelf.users = d
            },
            function(errResponse){
                console.error("Error while catching something"+errResponse);
            }
        );
}
}]);

users.html users.html

<div ng-controller="UsersController as ctrl">

      <table class="table table-hover" ng-init="ctrl.fetchAllUsers()">
          <thead>
          <tr>
              <th>ID.</th>
              <th>Name</th>
              <th>Address</th>
              <th>Email</th>
              <th width="20%"></th>
          </tr>
          </thead>
          <tbody>
          <tr ng-repeat="u in ctrl.users">
              <td>{{u.id}}</td>
              <td>{{u.username}}</td>
              <td>{{u.address}}</td>
              <td>{{u.email}}</td>
          </tr>
          </tbody>
      </table>

home.html (This is the root page) home.html(这是根页面)

<div>
    <h2>You have landed on the home page!!!</h2>

    <a ng-href="#/users">Click here to go to the next page...</a>

</div>

output 输出

在此处输入图片说明

The your problem hear is that this isn't the correct pointer for popolate the data in your ui. 您所听到的问题是, this不是在用户界面中填充数据的正确指针。 this is becouse javascript works differentry respect to java and other programming language. 这是因为javascript与Java和其他编程语言的区别。

whit this small changes the your code should works. 如果有这么小的更改,您的代码应该可以工作。

controller( "" , ... 

 this.user = {};
        this.users = [];
        var self = this;

        this.fetchAllUsers = function(){
            var uresSelf = self;

            usersService.fetchAllUsers()
                .then(
                function(d){
                    uresSelf.users = d.data
                },
                function(errResponse){
                    console.error("Error while catching something");
                }
            );
        }

the key point is how javascript, respect to the fact if you use "use strict" or no, when use this in function works ina partucular way remember tha function are objects in javascript even if you write a function js engine tract a function as an object and the this reference of the main function(the mani object) was different respect to the this of a inner function(onother object). 关键是javascript如何尊重事实,如果您使用“ use strict”或不使用,则在函数中以特殊方式使用此函数时,请记住,即使您将函数js引擎写成一个函数,该函数也是javascript中的对象对象和主函数(mani对象)的this引用与内部函数(另一个对象)的this有所不同。

The tipical workaround hear was that: Becouse you can't use this of the outer function in the inner function you create a reference in this way you througth the reference previously built can refer to the outer this in the inner funciotn. 常见的解决方法是:因为您不能以this方式在内部函数中使用外部函数的this ,所以您以前构建的引用可以在内部函数中引用外部的this。

function outerFunction(){

 var outerThis = this;

  function innerFunction(){
     console.log("this the this of the outer function" + outerThis );
     console.log("this the this of the inner function" + this);  
 }();

}

resuming I post all the code of the my poc for validate what I written: 继续发布我poc的所有代码以验证我写的内容:

the context configuration was: 上下文配置为:

@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}
@RestController
class FormRestController {

    @Autowired
    UserService userService;

    //-------------------Retrieve All Users--------------------------------------------------------

    @RequestMapping(value = "/users", method = RequestMethod.GET)
    public ResponseEntity<List<User>> listAllUsers() {

        System.out.println("listAllUsers() is being called inside RestController............");

        List<User> users = userService.findAllUsers();
        if (users.isEmpty()) {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
        return new ResponseEntity<>(users, HttpStatus.OK);
    }
}

@Data
@Builder
class User{

    private long id;
    private String username;
    private String address;
    private String email;
}

@Service
class UserService {

    public List<User> findAllUsers(){
        List<User> users = new ArrayList<>();

        users.add(User.builder().id(1).username("valerio").address("via sessa aurunca").email("v.vòg.v").build());
        users.add(User.builder().id(2).username("valerio1").address("via sessa aurunca").email("v.vòg.v").build());
        users.add(User.builder().id(3).username("valerio2").address("via sessa aurunca").email("v.vòg.v").build());
        users.add(User.builder().id(4).username("valerio3").address("via sessa aurunca").email("v.vòg.v").build());
        users.add(User.builder().id(5).username("valerio4").address("via sessa aurunca").email("v.vòg.v").build());

        return users;
    }
}

the htmo file was: htmo文件为:

<!DOCTYPE html>
<html lang="en" ng-app="myApp">
<head>
    <meta charset="UTF-8">
    <title></title>


</head>
<body>
<div ng-controller="UsersController as ctrl">

    <table class="table table-hover" ng-init="ctrl.fetchAllUsers()">
        <thead>
        <tr>
            <th>ID.</th>
            <th>Name</th>
            <th>Address</th>
            <th>Email</th>
            <th width="20%"></th>
        </tr>
        </thead>
        <tbody>
        <tr ng-repeat="u in ctrl.users">
            <td>{{u.id}}</td>
            <td>{{u.username}}</td>
            <td>{{u.address}}</td>
            <td>{{u.email}}</td>
        </tr>
        </tbody>
    </table>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
<script src="main.js"></script>
</body>
</html>

and the js file was: js文件是:

angular.module('myApp',[])
    .factory('usersService',['$http', '$q', function($http,$q){
        return {


            fetchAllUsers: function(){
                return $http.get('http://localhost:8080/users')
                    .then(
                    function(response){
                        return response;
                    },
                    function(errResponse){
                        console.error("Error while fetching customers");
                        return $q.reject(errResponse);
                    }
                );
            }
        }

    }]).controller('UsersController', function($scope, usersService){

        this.user = {};
        this.users = [];
        var self = this;

        this.fetchAllUsers = function(){
            var uresSelf = self;

            usersService.fetchAllUsers()
                .then(
                function(d){
                    uresSelf.users = d.data
                },
                function(errResponse){
                    console.error("Error while catching something");
                }
            );
        }
    });

I hope that i was clear in my answare and that can help you. 我希望我清楚知道该如何做,可以为您提供帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM