I am attempting to make multiple AJAX calls on my page using the $q
method. After receiving all the responses, I am trying to store them in a single array. However, it seems like this process is not functioning as expected.
Here is my controller:
I have used a for loop to iterate over multiple pages in an API and retrieve the JSON data.
$scope.items = [];
for (var i = 1; i < 10; i++) {
var apiURL = "https://swapi.co/api/planets?page =" + i;
searchData(apiURL).then(function(response) {
$scope.items.push(response[0].data.results);
});
}
$scope.showDetail = function(data) {
$scope.items = data.results;
$scope.items.sort(function(a, b) {
return a.population.localeCompare(b.population);
});
}
$scope.showDetail($scope.items);
$scope.highlighFont = function() {
}
And here is my Factory:
var app = angular.module('starApp');
app.factory('searchData', function($q, $http) {
return {
getResults: function(apiUrl) {
var promises = [];
var deferred = $q.defer();
$http({
method: 'GET',
url: apiUrl
}).then(function(data) {
deferred.resolve(data);
}, function(error) {
deferred.reject();
});
promises.push(deferred.promise);
return $q.all(promises);
}
};
});
If anyone could point out any errors in my approach, that would be greatly appreciated.