http获取请求在角度1中不起作用

时间:2017-02-22 19:17:11

标签: javascript angularjs http

我无法通过我的服务获取URL,即使我可以在浏览器中使用它。

" $ http()"似乎没有被调用。第一个警报()出现了,但就是这样。

这是在浏览器中返回的URL = http://localhost:8080/myapp/students

[{" ID":1,"名称":"丹尼斯""课程":[{" ID& #34;:1,"名称":" mycourse"}]}]

有人可以就我的错误提出一些建议吗?

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>

1 个答案:

答案 0 :(得分:0)

您忘记将$http添加为依赖项

将服务定义更改为以下代码:

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