Combining data from multiple API calls in a for loop with AngularJS

I'm working with an API that contains pages from 1 to 10 and my goal is to cycle through these page numbers to make the necessary 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;
}]);

After making all 10 API calls, I logged the data and you can see the results in this JSON data image.

However, when I try to display the list of names received from all 10 API calls, it seems like only the data from the last call is being used. How can I merge all the returned data into one object so I can display a complete list of names from pages 1 to 10?

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

In the view.html file:

<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>

Answer №1

To simplify handling multiple promises returned by the $http service, utilize $q.all to consolidate them:

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;
    }
});

How to use this in your code:

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

To dive deeper into this topic, visit AngularJS $q Service API Reference - all.

Answer №2

To successfully handle this situation, make sure to fulfill the promise first before appending the information to an array. Take a look at this example:

app.service('organizations', ['$http', function($http) {
    var storage = [];
    for (let num = 1; num < 11; num++) {
        $http.get('https://samplewebsite.com/wp-json/wp/v2/categories?per_page=50&page=' + num)
            .then(function(response) {
                console.log(response.data);
                storage.push(response.data);
            })
    }
    return storage;
}]);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

sending the properties from the menu component to the dish details

Having trouble with a react.js app I'm working on that involves rendering dish cards. The dish object is always null when passed as props from MenuComponent to DishDetail, resulting in nothing being displayed on the screen. Can someone please assist m ...

Eliminate any undefined data in the popup map of Javascript

I am working with JSON data that is being displayed in a pop-up on a map. In cases where there is missing data (Visibility), the word undefined appears in the pop-up. Is there a way to remove the undefined text so that it does not show up in the pop-up? ...

jQuery replacement for replaceChild method

I've been attempting to swap out an existing DOM element with a new one that I created. I attempted the following code snippet: $(this).parent().replaceChild(newElem,this); However, it resulted in an error message saying $(this).parent().replaceChi ...

Is there a way to specifically use nl2br() for just one row when sending everything to an array?

In our database, there are a total of 20 rows. One of the rows is structured as follows: 1) cool text 2) not really 3) something else? The rest of the rows contain one line of data each. When it comes to outputting a single row with line breaks, we ut ...

Error: VueJS mixins do not include the property definition

I've been trying to incorporate Mixins into my Vue.js code, but I've run into a few issues :/ Here's the current code for two test modules : ErrorBaseMixin.vue <script> import ErrorAlert from './ErrorAlert'; expor ...

Unable to locate module: '@material-ui/pickers' - Material UI React

I encountered an error that said: Material UI React - Module not found: Can't resolve '@material-ui/pickers' in React. Previously, I faced a similar issue with '@date-io/date-fns' but was able to fix it by updating to the latest ...

I am looking to send an ajax request from the themes directory's loyalty.tpl file to the LoyaltyModule.php file in PrestaShop version 1.6.1.5

How can I successfully send an ajax request from the theme file folder/loyalty.tpl to /public_html/test/modules/loyalty/LoyaltyModule.php in Prestashop 1.6.1.5? <input id="Gcash_id" name="Gcash_id" type="text" class="form-control grey" placeholder="Ent ...

Choosing items from a JSON array using 2 specific requirements

When it comes to retrieving the list of issue comments for a specific PR, I use the following curl command: curl -sH "Accept: application/vnd.github+json" -H "Authorization: token XXXXXXXXXX" https://api.github.com/repos/org/repo/issues ...

What is the process for defining default prop data in Next.js?

Currently, I am in the process of developing a React/Next app with CRUD functionality. In regards to the update form, I have included the code below which is responsible for fetching existing data and updating it via an API. However, there seems to be a ma ...

Passing multiple parameters in URL for APIs using Next.js

Is there a way to pass multiple parameters and retrieve results from the next.js API? I found the documentation very helpful, you can check it out here /api/posts/[postId].js The above setup works fine, but I want to know if it's possible to pass an ...

Performing a JavaScript/jQuery callback to server without the need for an accompanying executable backend

Today, a colleague in the tech world posed an interesting question to me: Can jQuery (or JavaScript in general) retrieve information about the filesystem from its source without the need for executable code? Initially, I instinctively responded by saying t ...

Implementing Autocomplete search with jQuery Chosen plugin - a step-by-step guide

CSS <select class="custom" id="company_hub" name="company_hub" style="width: 400px; display: none;"> <option>-Select Item-</option> </select> https://i.sstatic.net/x4YtN.png I attempted the following method but it was unsucces ...

Access another page by clicking on a link within an HTML document

Is it possible to include an anchor tag in demo1.html that, when clicked, will take the user to the demo2.html page and automatically select a data filter on that page? Here is the code snippet for demo1.html: <li> <div><a href="urunli ...

When the webpage first loads, the CSS appears to be broken, but it is quickly fixed when

Whenever I build my site for the first time, the CSS breaks initially, but strangely fixes itself when I press command + s on the code. It seems like hot reloading does the trick here. During development, I can temporarily workaround this issue by making ...

How can I ensure that my function only returns a value once the ajax call has finished?

Using mootools, I have a function that triggers an ajax script to retrieve a value. However, the function seems to return before the AJAX call is completed! What could be causing this issue... function getCredits() { var loadGlobalTab = new Request.J ...

Working with variables passed from Node.js in Jade processing

Currently, I have a situation where my script is sending a matrix that looks like this: [[1,2,3,4], [7,6,5,4], [2,3,4,5]]. After sending it using res.send(JSON.stringify(dataArray)); and viewing it in jade with h1#results, I can see that the format appears ...

Problems with displaying Wordpress content on your web browser

I am having trouble getting my website content to display properly in a web browser, even though I built it using Wordpress. It appears that only the logo and the 'Services' bar are showing up on the page, while the rest seems to be missing. I s ...

Utilize the datepicker function in jQuery version 1.6.3 to select a range of dates

I need help adding a jQuery datepicker to my JSP page for selecting a date range. Below is the current code I am working with. $(function() { $( "#createdAtFrom" ).datepicker({ defaultDate: "+1w", changeMonth: true, ...

Multiple loop in Node.js with Selenium

I just completed a node script using selenium webdriver for automated testing purposes. Below is the code snippet: var webdriver = require('selenium-webdriver'), By = webdriver.By, until = webdriver.until, _und = require('unders ...

Paragraph Separated by Bullets Without Bullets At End of Line

I need assistance in creating a unique type of list that I call a "bullet separated paragraph list" by using a javascript array of strings. For example: item • item • item • item • item     item • item • item • item item • ...