0

I'm trying to call multiple ajax in my page using $q. after all the response am storing in one array. but it seems not working correctly-

My controller-

used for loop to go over multiple pages in API and get the json.

        $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() {

        }

My Factory-

var app = angular.module('starApp');

app.factory('searchData', function($q, $http) {

  return function(apiUrl) {

    var promises = [];

    var deffered = $q.defer();

    $http({
        method : 'GET',
        url : apiUrl
    }).then(function(data) {
        deffered.resolve(data);

    }, function(error) {
        deffered.reject();

    })

    promises.push(deffered.promise);

    return $q.all(promises);
  }

 });

can someone correct me if am doing wrong??

Michael Doye
  • 8,063
  • 5
  • 40
  • 56
saurav
  • 3
  • 2
  • Possible duplicate of [resolve multiple promises in angularjs](https://stackoverflow.com/questions/42841865/resolve-multiple-promises-in-angularjs) – madalinivascu Nov 20 '17 at 12:00

1 Answers1

0

You need to call $q.all() in the controller

app.factory('searchData', function($q, $http) {

  return function(apiUrl) {
    return $http({
        method : 'GET',
        url : apiUrl
    });//$http returns a promise 
  }
 });

controller:

    $scope.promises = [];
            for (var i = 1; i < 10; i++) {
                var apiURL = "https://swapi.co/api/planets?page =" + i;
                    $scope.promises.push(searchData(apiURL));
            }

   $q.all($scope.promises).then(function(results){
       console.log(results);
   });
madalinivascu
  • 32,064
  • 4
  • 39
  • 55
  • thanks for pointing this out. but results contains response for 10 pages. it seems it contains json response from page 1 for 10 times. Is that something that needs to be taken care of? – saurav Nov 20 '17 at 15:22