Executing numerous GET requests with varying parameters in AngularJS

Update: My apologies to those who answered, it turns out that the code was correct, but requests were being intercepted and losing all parameters.


I am attempting to send repeated HTTP GET requests to a REST API based on the response, using the solution I found in this post.

However, I need to increment one of the parameters in each request. The API paginates the output and requires me to increase the value of startAt accordingly.

When I manually make the request with:

<URL>/board?startAt=50

I receive:

{"maxResults":50,"startAt":50,"isLast":true,"values":[list_of_values]}

This is my current code:

function getHttpPromise(start_at) {
    // This function recursively retrieves values until isLast is true.
    
    test = $http({
                    url: 'boards',
                    method: 'GET',
                    params: {'startAt': start_at.toString()}
                 }).
        success(function (response) {
            console.log(response);
            
            var values = response.values;
            for (var i in values) {
                var board = values[i];
                $scope.boards[board.id] = board;
            }

            if (response.isLast) {
                return true;
            } else {
                start_at += response.maxResults;
                return getHttpPromise(start_at);
            }
        }
    );

    console.log(test);

    return test;
}

This function is invoked by:

jiraWorkLog.controller('SprintSelectCtlr',
function($scope, $http, $routeParams) {
    $scope.init = function() {
        $scope.boards = new Object();

        getHttpPromise(0).then(
            function (dummy_var) {
            for (var board in $scope.boards) {
                ...
            }
        }
    );
}
...
);

Answer №1

When it comes to retrieving data from an HTTP response, the key is understanding how to parse and extract the information within.

If you're facing challenges with recursion in your code, consider checking out this resource for assistance: Angular Http

Furthermore, one common issue that may arise is mistakenly updating a local variable and misusing it within your implementation.

function getHttpPromise(start_at) {
// This function loops until the server indicates the retrieval process is complete.
//
// Each cycle appends the values in response.values to
// $scope.boards.
test = $http({
                url: 'boards',
                method: 'GET',
                params: {'startAt': start_at.toString()}
             }).
    success(function (response) {
        console.log(response.data); // The response includes startAt value as 0 instead of start_at's actual value

        var values = response.data;
        for (var i in values) {
            var board = values[i];
            $scope.boards[board.id] = board;
        }

        if (response.data.isLast) {
            // All boards have been retrieved.
            return true;
        } else {
            // Increment start_at and initiate another http request promise.
            return getHttpPromise(response.data.maxResults+1);
        }
    }
);

console.log(test); // Correct parameters are displayed here

return test;

}

Answer №2

The $http().success() method is no longer supported and has been deprecated. It is recommended to use the $http().then() method instead.

When using the then method, a function will be passed a response object which contains a property called data where you can access your desired values.

For more information, you can visit here

Upon closer examination of your code, I would advise against solving this issue recursively. If data pagination is not required, it is better to send a single request for all records at once.

To address why only the first result is being returned: this is because it is the only thing being returned and received by the calling controller. The controller awaits resolution of the promise, so any subsequent recursive calls occur after the controller has already finished processing.

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

Unravel and extract information from a JavaScript object using PHP

I am working with a variable called "type" in my code. var type = []; Within this variable, I am using the method push to add an object {'type' : 1}. type.push({'type' : 1}); After performing this operation, I end up with the follow ...

Azure experiencing issue with MUI Datepicker where selected date is shifted by one day

I have developed a unique custom date selection component that utilizes Material UI and Formik. This component passes the selected date value to a parent form component in the following manner: import React from 'react'; import { useField } from ...

Issue with readonly is preventing the ability to alter the font color of the input

I need to change the font color of a disabled input. When it is disabled, it appears gray and I want it to be black instead. I attempted to use readonly but that did not have the desired effect, and now the input is showing [object Object]. Below is my HTM ...

The type 'Event' argument cannot be assigned to the 'InfiniteScrollCustomEvent' parameter

I'm facing an issue with Ionic Angular. Here is my movies.page.html: <ion-header> <ion-toolbar color="primary"> <ion-title>Trending Movies</ion-title> </ion-toolbar> </ion-header> <ion-content ...

How can you troubleshoot code in NextJS API routes similar to using console.log?

Incorporating nextjs API routes into my upcoming project has been a priority, and I recently encountered an issue with code execution upon sending a POST request. Debugging has proven to be challenging since I am unable to use conventional methods like co ...

serverless with Node.js and AWS encountering a 'TypeError' with the message 'callback is not a function'

Within my handler.js file, I am utilizing the getQuotation() function from the lalamove/index.js file by passing the string "hi" as an argument. 'use strict'; var lalamove = require('./lalamove/index.js'); module.exports.getEstimate = ...

Utilizing Jquery-Menu-Aim to assign values to child scopes

Currently, I am in the process of developing a directive for jQuery-menu-aim. While my current implementation is functioning as intended, I can't help but feel that finding and setting values on the child scope seems like a workaround. You can view m ...

React JS - In order to display multiple children, consider utilizing an array rather than individual elements

Currently, I am employing React for my application and utilizing an API located at http://localhost:8080/api/suppliers/supplier/list to fetch data. Upon inspecting the Google Chrome console, this is the format of the data structure I am receiving: 0:{ ...

Creating a custom route that is specific to a single ejs file

I'm trying to set up a URL like localhost:3000/hh234due with a unique ID that routes to a specific page. However, my current implementation is conflicting with other routes. How can I make the /:id route unique to one view? module.exports = fun ...

Exploring the combination of Holder.js and Rails routes

What's the best way to integrate Holder.js into my Rails application? I'm running into issues where Rails is interpreting the parameters passed to the script as routes and returning 404 errors. Has anyone successfully implemented this before? ...

What is the process for acquiring a comprehensive catalog of Node.js modules?

Currently, I am working on integrating NPM functionality into my Node.js applications. My goal is to be able to analyze the node modules available on my system. When referring to a "module" in this context, it could either be an identifier like "fd" or a f ...

Encountering Server Error 500 while trying to deploy NodeJS Express application on GCP App Engine

My goal is to deploy a NodeJS app on gcloud that hosts my express api. Whenever I run npm start locally, I receive the following message: >npm start > [email protected] start E:\My_Project\My_API > node index.js Running API on por ...

Guide to converting raw Mysql fields into objects using Node.js

I have written a code to retrieve all the rows from the article table in MySQL, but I would like to represent this data in object and array format so that I can send it to endpoints. app.get('/article' , function(req , res){ var connec ...

How to prevent checkbox autocomplete from selecting the previously checked value using Jquery Ajax

Working on implementing the "Autocomplete ajax search" feature using Php. Successfully fetching data from the database. Currently, when searching for something, the results with checkboxes are displayed. However, when I search for a text, check a checkbo ...

Retrieving JSON data by key through ajax does not show the expected output

I'm currently working with JSON data in the form of an array, and I'm facing some issues. Here's how the data looks: [ { "id": 1, "name": "Leanne Graham", "username": "Bret", ...

Troubleshooting AngularUI's UI-sortable Index Update Problem

I've encountered a strange bug while using AngularUI's ui-sortable directive. Most of the time, dragging elements works smoothly and the index is updated when an element is moved to a new position. However, there are instances where the index doe ...

Using JavaScript to disable and re-enable an ASP.NET Timer control

I currently have a webpage built with ASP.Net that includes an ASP:Timer control <asp:Timer ID="TimerRefresh" runat="server" Interval="5000" Enabled="true" OnTick="TimerRefresh_Tick"> </asp:Timer> It is connected to an asp:UpdatePanel on the ...

Constantly loading image with Meteor HTTP request

Within my Meteor application, I am attempting to dynamically load a random image from an API which returns JSON data structured like this: { "id":2026 "url": "https:// ... " , "large_url":null, "source_id":609, "copyright":"CC0", "site":"unsplash" } ...

Ways to extract information from a text

I have a massive string, divided into two parts that follow this pattern: {\"Query\":\"blabla"\",\"Subject\":\"gagaga"}", {\"Query\":\"lalala"\",\"Subject\":\"rarara&bso ...

"An ng-repeat directive with a filter applied results in an empty

After successfully implementing the ng-repeat loop below: <div ng-repeat="einschItem in einschaetzungen.alldata | filter: { savedatum: lolatage[tagarrayindex].tagestring } | orderBy : '-savetimestamp'"> I wanted to check if the filtered r ...