1

I have this API that has pages 1-10 and I want to loop through the page numbers to make the API calls

app.factory('companies', ['$http', function($http) {
    var i;
    for (i = 1; i < 11; i++) {
        var data = $http.get('https://examplepage.com/wp-json/wp/v2/categories?per_page=50&page=' + i);
        console.log('list', data);
    }
    return data;
}]);

This is what I get when I console log the data for all 10 API calls JSON data

My attempt to display all of the data (list of names), but it seems as though it's only taking the last API call and displaying it. How do I combine all of the returned data into one object to display the list of name from pages 1-10?

app.controller('HomeController', ['$scope', 'companies', function($scope, companies) {
    companies.success(function(data) {
        $scope.companies = data;
        console.log('companies', $scope.companies);
    });
}]);

view.html

<div class="container" ng-controller="HomeController">
        <div ng-repeat="company in companies" class="list">
            <a href="#/{{ company.id }}" class="company-name">{{ company.name }}</a>
        </div>
</div>
1

2 Answers 2

1

Each call to the $http service returns a promise. You need to use $q.all to consolidate the promises:

app.factory('companies', function($http,$q) {
    return { tenPagesPromise: tenPagesPromise };

    function tenPagesPromise () {
        var indices = Array.from({length:10}).map((x,i)=>i);
        var promises = indices.map(i=>pagePromise(i));
        return $q.all(promises).then(responseArray => {
            var dataArray = responseArray.map(x=>x.data);
            return dataArray.reduce((t,x)=>t.concat(x),[]);
        });
    }

    function pagePromise(i) {
        var url = "https://examplepage.com/wp-json/wp/v2/categories";
        var params = { per_page: 50, page: i };
        var config = { params: params }
        promise = $http.get(url,config);
        return promise;
    }
});

Usage:

companies.tenPagesPromise.then(data => {
    $scope.companies = data;
}).catch(function(errorResponse) {
    console.log(errorResponse);
});

For more information, see AngularJS $q Service API Reference - all.

Sign up to request clarification or add additional context in comments.

Comments

0

You need to resolve the promise and then add the data to an array, something like this:

app.factory('companies', ['$http', function($http) {
    data = []
    for (let i = 1; i < 11; i++) {
        $http.get('https://examplepage.com/wp-json/wp/v2/categories?per_page=50&page=' + i)
          .then( function(resp) {
             console.log(resp.data);
             data.push(resp.data);
           })
    }
    return data;
}]);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.