Reputation: 7
I am trying to teach myself building RESTful API's and I am just using angular to try to display what I retrieve. I can see in the console that my RESTful call works as it is returning data. However when it is doing the assignment it seems like it all gets lost.
I feel like I am overlooking something simple but I've been staring at it so long now that I have come to seek some help.
Thanks
This is my 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>
This is my 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;
});
Upvotes: 0
Views: 1202
Reputation: 6348
Factories should return an object that is used to query data. It shouldn't return data itself.
.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;
}
});
Upvotes: 1
Reputation: 11754
This is what your code should look like:
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();
or use $http
.factory('employeeService', function ($http) {
return $http.get('http://localhost:8060/RESTExample/REST/WebService/Employee');
Upvotes: 2