我正在尝试自己构建RESTful API,我只是使用angular来尝试显示我检索的内容。我可以在控制台中看到我的RESTful调用正在返回数据。然而,当它进行任务时,似乎一切都会丢失。
我觉得我忽视了一些简单的事情但是我已经盯着它看了很长时间以至于我来寻求帮助。
由于
这是我的index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>HR Test</title>
</head>
<body>
<div ng-app="myApp" ng-controller="EmployeeCtrl">
<table>
<tr ng-repeat="employee in employeeList">
<td>{{employee.firstName}}</td>
<td>{{employee.lastName}}</td>
</tr>
</table>
</div>
<script type="text/javascript" src="angular.min.js"></script>
<script type="text/javascript" src="angular-resource.min.js"></script>
<script type="text/javascript" src="main.js"></script>
</body>
</html>
这是我的main.js
var myApp = angular.module('myApp', ['ngResource'])
.controller('EmployeeCtrl', function($scope, $resource, employeeService) {
// employeeService here has nothing
$scope.employeeList = [employeeService];
})
.factory('employeeService', function ($resource) {
var source = $resource(
'http://localhost:8060/RESTExample/REST/WebService/Employee');
var data =source.query({},function(){
//this log shows the data
console.log (data);})
return data;
});
答案 0 :(得分:2)
这就是你的代码应该是这样的:
var myApp = angular.module('myApp', ['ngResource'])
.controller('EmployeeCtrl', function($scope, $resource, employeeService) {
// employeeService here has nothing
//$scope.employeeList = [employeeService]; // incorrect, you're assigning a service into the first element of an array
employeeService.then(function(success){
$scope.employeeList = success.data;
}, function(error){
});
})
.factory('employeeService', function ($resource) {
return $resource('http://localhost:8060/RESTExample/REST/WebService/Employee').get();
或使用$ http
.factory('employeeService', function ($http) {
return $http.get('http://localhost:8060/RESTExample/REST/WebService/Employee');
答案 1 :(得分:1)
工厂应返回用于查询数据的对象。它不应该自己返回数据。
.controller('EmployeeCtrl', function($scope, $resource, employeeService) {
// employeeService here has nothing
employeeService.getEmployees().then(function(data){
$scope.employeeList = data;
});
})
.factory('employeeService', function ($resource) {
return {
getEmployees: function() {
var source = $resource(
'http://localhost:8060/RESTExample/REST/WebService/Employee');
return source.get().$promise;
}
});