I am working with a data set where I want to get the name and position of the staff member rostered on for a particular day.
The problem is the data is seperated in three different endpoints so I need to connect them all to get the meaningful data I am after.
endpoints /team (team rostered on for today)
[{
"employeeID": "111"
},
{
"employeeID": "333"
},
{
"employeeID": "444"
}]
/staff/:employeeID (name-staffID.json in plnkr)
{
"employeeID": "111",
"firstName": "Tom",
"lastName":"Smith"
}
/role/:employeeID (role-staffID.json in plnkr)
{
"roleID": "1",
"employeeID": "111",
"role": "Manager"
}
I have the below code working in this plnkr but what I cant work out is whether I can rely on getting the data when I have $scope.team after my API calls. When I console.log the array todaysTeam it comes back with []. Is there a better way to handle this situation eg after forloop is complete set $scope.team or is the approach I have gone with reliable.
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.14/angular.min.js"></script>
<script src="script1.js"></script>
</head>
<body>
<div ng-app="App">
<div ng-controller="MainCtrl">
<ul>
<li ng-repeat="t in team">{{t.firstname}} is the {{t.role}}</li>
</ul>
</div>
</body>
</html>
JS:
(function () {
function MainCtrl($scope, APIService) {
function getTeams() {
var todaysTeam = [];
APIService.getTeam()
.success(function (data) {
for (var i in data) {
//console.log(data[i].employeeID);
APIService.getStaff(data[i].employeeID)
.success(function (staff) {
APIService.getRole(staff.employeeID)
.success(function (role) {
console.log(staff.firstName + ' is the ' + role.role);
todaysTeam.push({
"firstname": staff.firstName,
"role": role.role
});
console.log(todaysTeam);
});
});
}
});
console.log(todaysTeam);
$scope.team = todaysTeam;
}
getTeams();
}
function APIService($http) {
var APICalls = {};
APICalls.getTeam = function () {
return $http.get('team.json')
.success(function (data, status, headers, config) {})
.error(function (data, status, headers, config) {});
};
APICalls.getStaff = function (staffID) {
return $http.get('name-' + staffID + '.json')
.success(function (data, status, headers, config) {})
.error(function (data, status, headers, config) {});
};
APICalls.getRole = function (staffID) {
return $http.get('role-' + staffID + '.json')
.success(function (data, status, headers, config) {})
.error(function (data, status, headers, config) {});
};
return APICalls;
}
angular.module('App', [])
.controller('MainCtrl', MainCtrl)
.factory('APIService', APIService);
})();