I am having trouble figuring out proper use of angular's $q
and Javascript's promise
api. Then again, I am pretty new to Javascript, and may be making a syntax error.
This question seems similar, but it doesn't seem to be an exact copy...
My service has a method like this (called by my controller):
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;
};
And my controller passes the returned promise list 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 my HTML, I try to iterate over and display the resources:
.
.
.
<!-- 'cars' is and 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>
The table is not displaying any results.
I can see from the console that the HTTP requests are successful and returning data, so I must be making a mistake with either the promise
or $q
apis.
Any suggestions?
Thanks much.