Dealing with numerous ajax requests simultaneously with the help of $q.all

I am attempting to make multiple AJAX calls on my page using the $q method. After receiving all the responses, I am trying to store them in a single array. However, it seems like this process is not functioning as expected.

Here is my controller:

I have used a for loop to iterate over multiple pages in an API and retrieve the JSON data.


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

}

And here is my Factory:


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

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

    return { 
        getResults: function(apiUrl) {
            var promises = [];

            var deferred = $q.defer();

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

            promises.push(deferred.promise);

            return $q.all(promises);
        }
    };
});

If anyone could point out any errors in my approach, that would be greatly appreciated.

Answer №1

Ensure to utilize $q.all() within the controller

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

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

controlling script:

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

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

The screen reader seems to be malfunctioning as soon as I include this particular code

//Finding the height of the header let headerHeight = document.querySelector('header'); let height = headerHeight.offsetHeight; //Adjusting the #navbarNav's top margin to accommodate the header let nn = docu ...

HTML/Bootstrap - carousel malfunctions and no longer functional

Once I had a beautiful carousel scrolling through 4 images flawlessly. I made some updates to another section of the website, and now the carousel has stopped responding altogether. It doesn't cycle through the images automatically, and the buttons or ...

HTML - Transforming JSON data into a table

I'm having trouble converting JSON data into a table format. Although everything seems to be in order, I am unable to view the values on my table. Here is the code I am using to convert JSON to a table: $(function() { var my_data = &ap ...

Angular: Assigning a key from one variable to a value in another

I am currently facing a challenge with rendering a form on a page using ng-repeat, where the data for this form is dynamically fetched from a request. Within this data, there is a nested array called "categories" which contains IDs. I want to display the n ...

Determine the execution time of a Python script

I have developed a series of Python scripts to run as the backend of my application. Users are required to upload a file using the provided webpage, where they can track the progress through a displayed progress bar. The file is broken down into frames, ob ...

The image next to the words

Hey there, I'm looking to add a photo next to some text on my page using flexbox. I was able to achieve something similar but I'm open to other suggestions. Check out what I have so far here and here's the desired look: It should look like ...

Steps to convert HTML <li> elements into HTML <datalist> elements

In my HTML file, I have a list of objects within li elements that I would like to transfer to an HTML datalist within the same file. I am currently working on a Node.js Express framework application where the data within the li elements is coming from an S ...

Opera's extra space feature allows users to comfortably browse the

I'm attempting to insert a progress bar inside a td element within my table. Below is the code: <td style="width: 150px;"> <div style="height: 16px; max-height: 16px; overflow: hidden; border: 1px solid #80C622;"> < ...

Step-by-step guide on achieving 100% height for the <main> element in a Material UI drawer demo

I have a question regarding the Material UI drawer. In my project, I am trying to change the background color of the main tag. However, the main tag's height is restricted to the content inside. Check out this link for reference Setting the height t ...

Implementing asynchronous image loading with Angular 4 using bearer headers

Currently, I am working on making asynchronous image requests with authentication headers. The image paths in the code look like this: <img src="{{file.src}}"/> I need to include a Bearer Token in the header for these requests, but since there are ...

Automatically changing the page's background color through animation upon loading

Similar Question: jQuery animate backgroundColor Can I make the background-color of a specific element change gradually when the page loads? I have a webpage with content like this: <ul> <li> Some stuff</li> <li> Some ...

What is the best way to reference the className within nested SCSS when working with Next.js and React.js?

I am working on customizing a navbar that includes a hamburger button. My goal is to change the style, specifically the bar color and the appearance of the hamburger button, upon tapping. I have already attempted using &:active and .activeBar in the SCSS f ...

Integrating an AngularJS service into a controller

Currently working on a straightforward AngularJS app that features a game, home view, and game over view. I've shared most of the code below: http://jsfiddle.net/Seasamh/5bqq1bj8/ Here are the html templates: home.html <span>This is the ...

Smooth Slide-in Animation

I've been working on improving my understanding of animations, but keyframes are still a bit confusing for me. To help with my learning process, I decided to create a simple box slider that fades in each layer and then repeats the process. My goal is ...

What is the process for assigning a background color to a specific option?

Trying to create a dropdown menu with various options and colors. Managed to set background colors for each option, but once an option is selected, the background color disappears. Is there a way to fix this issue? See my HTML example below: <select> ...

Display intricate header and preview in a printed datatable

Hey there, I've been using the Datatable plugin and it's really great. However, I've come across a problem with complex headers like this: <thead> <tr><td>some text</td></tr> <tr><td>some te ...

Enhancing the Angular Currency Pipe to display zeros after the decimal point

Using Angular has strict requirements for displaying full numbers received from the backend. In some cases, like with "123.450" and "123.45," the amount may be the same but clients prefer to see the complete number. <td>{{ material.customerPrice | ...

Connecting to another page based on data list selection

I have created a datalist with multiple options and now I want to redirect to another page when one of the options is selected. Here is my initial attempt where I tried to directly add a hyperlink to the option label, but it didn't work as expected. ...

What is the process for displaying data within an Angular 10 component?

As I embark on my journey with Angular 10, my goal is to display the current user in the profile.component.html and the navbar in app.component.html. Below you will find the relevant code snippets: users.ts export interface User { username : string ...

Upon triggering an ajax post request, the HTML elements do not refresh as expected within an Angular environment

I am facing an issue where I make an AJAX POST request and it executes properly. After receiving the response, I need to make another AJAX GET request and assign the data to variables in the scope. The data is successfully assigned to the variables, but th ...