D
D
Dmitry Spiridonov2014-12-03 21:09:22
Angular
Dmitry Spiridonov, 2014-12-03 21:09:22

Angular - promise in a loop, and how to get data on each iteration?

Good afternoon! Tell me, please, how is it possible with such a code, in the controller to receive data from the service at each iteration.
Routing

'profiles': {
  controller: 'profilesList',
  templateUrl: '/partials/profiles/profiles.list.html',
  resolve: {
    profiles: function(dataservice) {
      return dataservice.getProfiles();
    }
  }
}

Service:
function getProfiles() {
  var promises = _.range(pages).map(function(page) {
    var deffered  = $q.defer();

    $http
      .get('http://api/v1/profiles?page=' + page)
      .success(function(data) {
        // тут мое непонимание
        deffered.resolve(data);
       })
       .error(function(error) {
        deffered.reject();
       });

    return deffered.promise;
  });

  $q.all(promises).then(function() {
    //
  });
}

And in the controller itself is also a snag. I understand that I can wait for all the promises and take the data in a bunch, but the bottom line is that there are a lot of profiles, waiting for everything is inexorably long. With this code, when I try to just stick return data into success, I will only see the first promise, because in the console I see that the data has arrived, and then everything stops, there is not even an error. Actually I ask you to direct me to the right path. Thanks in advance!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ilya, 2014-12-03
@spirAde

On the server to give pages. Loop through pages in Angular. Then just add your next profile page to the end of the array. For example like this:

function() {
          return $http.get(''http://api/v1/profiles?page=' + page).then(function (result) {
              $scope.page += 1;
              return angular.forEach(result.data, function (item) {
                  return $scope.profiles.push(item);
                      });
                  });
              };

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question