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

Having trouble with the JSON format within the 'operations' field in the formData of your Next.js application?

I encountered a mutation that looks like this- mutation signUp($avatar: Upload!) { signUp( avatar: $avatar input: { name: "Siam Ahnaf" email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail= ...

What steps do I need to take in order to ensure that each webpage displays unique thumbnails?

As a newcomer to website development, I recently looked into implementing open graph on my site. However, I ran into an issue where I could only set one thumbnail for the entire website. This posed a problem as I wanted each navigation menu tab (Home, Abou ...

Synchronization issue between CSS style and Javascript is causing discrepancies

I am looking to avoid using jquery for simplicity. I have three websites that each page cycles through. My goal is to scale the webpages by different values. I attempted applying a class to each page and used a switch statement to zoom 2x on Google, 4x o ...

Using Yii to attach an onclick event to CLinkPager for every pager link

Is there a way to execute a function with every pager link click in Yii's CLinkPager? I've tried the following code without success. 'pagerCssClass' => 'pagination', 'afterAjaxUpdate'=>"FB.Canvas.scrollTo ...

Is there a way to showcase all the information in products while also organizing it in the same manner that I have?

I am looking to sort prices while displaying all the properties of products at the same time. DATA INPUT: const products = [ { "index": 0, "isSale": true, "isExclusive": false, "price": "Rs.2000", "productImage": "product-1.jpg", ...

What distinguishes between the methods of detecting falsy and truthy values?

While working with JavaScript / Typescript, I often find myself needing to verify if a length exists or if a value is true or false. So, the main query arises: are there any differences in performance or behavior when checking like this... const data = [ ...

"Exploring the Mini Drawer feature on Material UI brings up a whole new page for the Link

Currently, I am working on a project that involves updating stocks using Material UI. I have implemented a mini drawer from Material UI, but when I click on the menu link, it routes to a new page instead of rendering on the homepage itself. In my App.JS f ...

Locate the selected radio button's label

There are 25 radio button groups on my page. Each group has a specific action that needs to be performed when a radio button is selected. In order to execute the correct action for each group, I require the NAME attribute of that particular radio group. ...

Streamline your processes by automating jQuery AJAX forms

I am looking to automate a click function using the code snippet below in order to directly submit form votes. Is there a method to develop a standalone script that can submit the votes without requiring a webpage refresh: <input type="submit" id="edit ...

A server-side rendered page in Next.js that functions without the need

Hey everyone, I'm curious about the best way to serve an HTML page in a Next Js application without relying on additional JavaScript. I need this because I want to make sure my webpage can be accessed by users who have older phones like Symbian or oth ...

Angular handling multiple query parameters

I am looking to implement multiple path routes for a component named Component2. I want the functionality to be similar to GitHub's file navigation within repositories, but I do not want to hardcode a path like 'source/:filePath/:filePath/:filePa ...

Encountering issues with sbrautaset's JSON-framework Objective-C: Receiving null when parsing objectWithString

I have encountered an issue with my Python code for Google App Engine. It is supposed to respond with the string {"sample_list": [{"message": "Hello, world.", "name": "Human"}]}. To convert this string into an object that I can utilize (specifically NSDict ...

Check if certain entries in the JSON object already exist by iterating through it

As I work on iterating over a JSON object to verify the existence of certain entries, my current JSON data structure is outlined below: [ { "title": "scname", "html": "<div><iframe src=/scenario/test3dx ...

Utilize underscore's groupBy function to categorize and organize server data

I am currently utilizing Angular.js in conjunction with Underscore.js This is how my controller is structured: var facultyControllers = angular.module('facultyControllers', []); facultyControllers.controller('FacultyListCtrl', [' ...

Utilizing the Twitter API 1.1 to retrieve a list of tweets

As I work on updating my CMS component, I am incorporating integration with the Twitter API to fetch and showcase a list of tweets related to a user or search query. I have chosen to utilize the Twitter Restful API v1.1 as the 1.0 version is set to be disc ...

Tips for adding a sequence of numbers to a database using Angular

How can I add a range of numbers to a database using a form? <form> <input class="form-control"></input> <!-- enter first number --> <input class="form-control"></input> <!-- enter last number --> ...

Guide on how to reference the Html directory using the path module in Node Js

Desperately trying to send an html file as a response using express, but I'm having trouble locating the position or path of the index.html file. This is how my files are structured - MyWebsite Html index.html Css index.css ...

Exploring JavaScript Object-Oriented Programming (OOP) concepts. Delving into the

Here is a sample of JavaScript OOP that I am currently studying. I'm puzzled about why getA() and getC() are returning undefined, but getB() returns 2 when I update the variable B in the constructor and assign it to b. When I execute getD(), it appea ...

Creating a custom Chrome extension with the ability to modify the pop-up window instead of the web page

Is there a way to modify the content inside my extension's pop-up without affecting the web page being viewed by the user? Also, how can I ensure that my dropdown list functions correctly? I have two dropdown lists where selecting an option from the ...

Is it possible for a method within a class to retrieve properties from a different object within the same class?

I'm facing an issue with accessing the necessary object properties within a method. In my scenario, I have a Game class that generates a new game object. Once the object is created, I attempt to execute the draw method. This draw method requires infor ...