简体   繁体   中英

http get request is not working in angular 1

I am unable to get the URL to work via my service even though I can get it to work in the browser.

The "$http()" doesn't seem to get invoked. The first alert() comes up, but that is it.

This is what come back in the browser for the URL = http://localhost:8080/myapp/students

[{"id":1,"name":"denis","courses":[{"id":1,"name":"mycourse"}]}]

Can someone make some suggestions as to what I am doing wrong?

studentform.js:

    "use strict";
angular.module('StudentApp',[]);
angular.module('StudentApp').service('StudentModel', [function($http){
    this.students = [{name:"NONE"},{name:"NONE2"}];
    this.getStudents = function(){
        alert("getStudents called.");
        $http({method: 'GET', url: 'http://localhost:8080/myapp/students'}).
            then( function(data, status, headers, config){
                alert("Success!!");
                this.students = data;
            }).
            catch( function(data, status, headers, config){
                alert("Failed!!");
                console.log( "Error: " + status );
            });
//      $http.get('http://localhost:8080/myapp/students')
//      .then( function (response) {
//          this.students = response.data;
//      }. bind( this), function (response) {
//          console.log( response.data);
//      }); 
//      $http.get('http://localhost:8080/myapp/students')
//      .then(function(response){
//          alert( "in then");
//          alert( response.date );
//          this.students = response.data;
//      }.bind(this),function(response){
//          alert( "in bind" );
//          console.log(response.data);
//      });
//      alert(response.data);
    }
}]);
angular.module('StudentApp').controller('StudentController', ['StudentModel', function(StudentModel){
    this.model = StudentModel;
}]);

studentform.jsp

    <!DOCTYPE html>
<html ng-app="StudentApp">
<head>
    <meta charset="UTF-8">
    <script src="/myapp/resources/js/angular/angular.js"></script>
    <script src="/myapp/resources/js/studentform.js"></script>
    <title>Students</title>
</head>
<body ng-controller="StudentController as main">
    <div>
        <p><button ng-click="main.model.getStudents()">Get Students</button></p>
        <ul>
            <li ng-repeat="student in main.model.students">
                {{student.name}}
            </li>
        </ul>
    </div>
</body>
</html>

You forgot to add $http as a dependency

Change your service definition to below code:

angular.module('StudentApp').service('StudentModel', ['$http', function($http){

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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