Struggling with understanding the correct utilization of Angular's $q
and JavaScript's promise
API. As a newcomer to Javascript, it's possible I'm making a syntax error.
This question appears similar, but isn't an exact duplicate...
The method in my service (called by the controller) looks like this:
self.getResources = function() {
let promises = [];
for (let resourceName in $rootScope.resourceNameList) {
promises.push($http({
url : '/' + resourceName,
method : 'GET'
}).then(function (res) {
return { resourceName : res.data};
}));
}
return promises;
};
The controller passes the promise list returned into Angular's $q.all()
:
let promises = resourceService.getResources();
$q.all(promises).then(function (resultsArray) {
// resultsArray should be an array of elements like:
// [ {cars : [...]}, {coffeePots : [...]}, {motorBoats : [...]} ]
// with size = resourceNameList.length(), correct?
// this log is never called.
console.log(resultsArray);
$scope.resources = resultsArray;
});
Finally, in the HTML code, I attempt to loop through and display the resources:
.
.
.
<!-- 'cars' is an example, but I am trying to retrieve this data in the same way -->
<tr ng-repeat="item in resources[cars]">
<td>{{item.property1}}</td>
<td>{{item.property2}}</td>
</tr>
No results are showing up in the table.
Despite successful HTTP requests that return data visible in the console, there seems to be a mistake with either the promise
or $q
APIs.
Any recommendations?
Thank you!