使用AngularJS进行简单的AJAX调用

时间:2016-12-14 16:28:36

标签: javascript angularjs ajax http

我是Angular JS的新手,只是想学习基础知识。我认为我有一个问题,将JSONObject分配给$ scope.talks。该表现在显示任何值。

这里我调用了一个JSONObject:

<script type = "text/javascript">
var myApp = angular.module('myApp',[]);
myApp.factory("EventsService", function ($http, $q) {
 return {
 getTalks: function () {
 // Get the deferred object
 var deferred = $q.defer();

 // Initiates the AJAX call
 $http({ method: 'GET', url: 'http://localhost:8080/greeting'
}).success(deferred.resolve).error(deferred.reject);
 // Returns the promise - Contains result once request completes
 return deferred.promise;
 }
 }
});
myApp.controller("HelloWorldCtrl", function ($scope, EventsService)
{
 EventsService.getTalks().then(function (talks) { 
 $scope.talks = talks.data
}, function ()
 { alert('error while fetching talks from server') })
});
</script>

调用返回的JSONObject如下:

{"talks":[{"duration":"45","venue":"5","speaker":"bill gates","name":"test","id":"45"},{"duration":"45","venue":"2","speaker":"bill gates","name":"another test","id":"33"}]}

以下是呈现数据的代码:

<body ng-app="myApp" ng-controller = "HelloWorldCtrl" style="font-family: Verdana, Geneva, 'DejaVu Sans', sans-serif">
<table class ="table table-condensed table-hover">
<tr>
<th>Id</th>
<th>Name</th>
<th>Speaker</th>
<th>Venue</th>
<th>Duration</th>
</tr>
<tr ng-repeat = "talk in talks">
<td>{{talk.id}}</td>
<td>{{talk.name}}</td>
<td>{{talk.speaker}}</td>
<td>{{talk.venue}}</td>
<td>{{talk.duration}}</td>
</tr>
</table>
</body>

2 个答案:

答案 0 :(得分:1)

您的回复对象中没有talks.data属性。

{"talks":[{"duration":"45","venue":"5","speaker":"bill gates","name":"test","id":"45"},{"duration":"45","venue":"2","speaker":"bill gates","name":"another test","id":"33"}]}

您应该将范围变量指定为

$scope.talks = talks.talks

控制器看起来像

myApp.controller("HelloWorldCtrl", function ($scope, EventsService)
{
 EventsService.getTalks().then(function (talks) { 
 $scope.talks = talks.talks
}, function ()
 { alert('error while fetching talks from server') })
});

答案 1 :(得分:0)

getTalks函数必须类似于:

getTalks: function () {
   return $http.get('http://localhost:8080/greeting');
 }

Angular方法$http将返回一个承诺。在您的代码中,您将在内部返回承诺另一个承诺。我的代码修复了它并使其更清晰。

然后,在您的控制器中,输入:

myApp.controller("HelloWorldCtrl", function ($scope, EventsService) {
    $scope.talks = EventsService.getTalks().then(
        function(res) {
            return res.data;
        }, 
        function(err) { 
           console.log("An error has ocurred!", err);
        }
    )
});

使用then()你正在解决这个承诺。在您的代码中使用JavaScript控制台而不是警报或打印是一种很好的做法。

祝你好运!