I'm working on an $http call that loops over each of multiple api's and returns all of the data in one object. I usually have the promise ready to resolve when the $http call has been made. Similar to this:
function getAllData(api) {
return $http({
method: 'GET',
url: '/api/' + api
})
.then(sendResponseData)
.catch (sendGetVolunteerError);
}
The current function I have loops over each api and pushes each object in the api into an array and then pushes it into an overall array. I had this functioning, returning an multi-dimensional array, which needed to be flattened out.
I'd like to return this in a promise, but am returning undefined
. Here is what I have so far? Is there a better way to approach this?
dataService:
function getSearchData() {
return {
loadDataFromUrls: function () {
var apiList = ["abo", "ser", "vol", "con", "giv", "blo", "par"];
var deferred = $q.defer();
var log = [];
angular.forEach(apiList, function (item, key) {
var logNew = [];
$http({
method: 'GET',
url: '/api/' + item
}).then(function (response) {
angular.forEach(response.data, function (item, key) {
this.push(item);
}, logNew);
return logNew;
});
this.push(logNew);
}, log);
$q.all(log).then(
function (results) {
deferred.resolve(
JSON.stringify(results))
},
function (errors) {
deferred.reject(errors);
},
function (updates) {
deferred.update(updates);
});
return deferred.promise;
}
};
};
Controller:
function getSearchData(){
return dataService.getSearchData.loadDataFromUrls;
}
$scope.searchData = getSearchData();
logNew
) to thelog
array, which you want to wait for? Should you not be pushing thepromise
returned by$http
instead? – Licorice