I am working on a call to $ http, which iterates over each of several api and returns all the data in one object. I usually have a promise ready to be resolved when a call to $ http was received. 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 a shared array. I had this functioning, returning a multidimensional array that needed to be smoothed out.
I would like to return this as a promise, but return undefined . Here is what I still have? 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();
byrdr source share