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

Each slider only displays a single database entry

I have an array that retrieves testimonials from a database table and displays them using a foreach loop. I am looking to implement a slider that can fade in and fade out the results. Here is my database query: $showTestimonials = array(); $getTestimoni ...

Animation of scrolling in a horizontal layout

Currently, I am utilizing ng-repeat 1.4 to dynamically generate elements within a div that has polymer shadow classes and uses the 'layout horizontal' style, resulting in code similar to: <div class='layout horizontal'> < ...

Is it possible to choose tags from a different webpage?

Imagine you have a page named a.html which contains all the jQuery code, and another page called b.html that only includes HTML tags. Is it feasible to achieve something like this: alert( $('a').fromhref('b.html').html() ); In essence ...

Clicking on links will open them in a separate tab, ensuring that only the new tab

Is there a way to open a new tab or popup window, and have it update the existing tab or window whenever the original source link is clicked again? The current behavior of continuously opening new tabs isn't what I was hoping for. ...

Guiding you on exporting a Typescript class with parameters in Node.js

Trying to find the Typescript equivalent of require('mytypescriptfile')(optionsObject); This is the TS code provided: export class Animal { name: string; public bark(): string { return "bark " + this.name; } constructor(color:string) ...

Tips for maintaining the JSON data on my server up-to-date

I have a question about my architecture. My backend system is built using Spring MVC with MongoDB. The JSON objects are exchanged between the backend and frontend, with the frontend being developed in HTML + AngularJS. None of the processing on the fronten ...

Execute an AJAX post request to the identical PHP page (utilizing the Jquery Form Plugin)

I am in the process of developing a new web interface using JavaTMP, an AJAX-based admin template. After spending time understanding its functionality, I have created a page with a form to allow users to create projects within my software. Typically, creat ...

Trouble arises when attempting to add an image to a spherical object

I've searched through various threads, Googled extensively, watched YouTube tutorials.... But I can't seem to figure out how to apply a texture to my Sphere. When I run this code, all I see is a white Sphere without any texture showing up. Can so ...

Vue 3 feature: Click the button to dynamically insert a new row into the grid

Just starting out in the world of coding, I've zero experience with Vue - it's my introduction to frameworks and arrays are currently my nemesis. In a recent exercise, I managed to display the first five elements of an array in a table after filt ...

Setting up a custom global variable in nuxt.js using vuetify

As I work on developing my app with Nuxt, I find myself frustrated by the need to constantly write an if statement in my pages using this.$Vuetify.breakpoint.name == 'xs' for handling responsiveness. Instead, I want to create my own variable for ...

Understanding Aspect Ratios in CSS for Div Containers and their Components

I am crafting an HTML5 game without the use of canvas and aiming to maintain a 16:9 aspect ratio within my div. Thanks to javascript, achieving this is straightforward and it functions flawlessly. However, the elements inside the div occasionally appear to ...

Modifying specific attributes of an object within the $scope: A step-by-step guide

When working with Angular, if you have code in the view that looks like this: <span ng-model="foo.bar1"></span> <span ng-model="foo.bar2"></span> <span ng-model="foo.bar3"></span> Due to how Angular maps objects, you c ...

having trouble with npm installation of firebase-tools

I am encountering an issue while attempting to set up firebase-tools for my android studio project. Here is the error message that I am facing: Microsoft Windows [Version 10.0.15063] (c) 2017 Microsoft Corporation. All rights reserved. C:\WINDOWS&bs ...

Harnessing the power of service binding in AngularJS

I am utilizing a service to facilitate data sharing between two controllers and retrieve a list of data: myApp.service('DataService', function($http) { this.data = []; this.loadData = function() { $http.get('/api/data') ...

Ways to refine data using multiple criteria

I have a list of alarm data that I need to filter based on specific conditions. If there are multiple alarms of type "pull_Alarm" and "emergency_alarm" in the same location, I want to prioritize the "emergency_alarm". Here is my list: [ { ...

Concealing functions within Accessors

I've recently started working on a website project utilizing the node.js/express stack and I am experimenting with developing in the functional programming style, which is quite new to me. One issue I encountered was related to the express method res. ...

JavaScript, change syntax from arrow to regular

Currently I'm in the process of learning and grasping JavaScript. In a tutorial video that I'm following, the instructor utilized this specific code snippet: app.post('/content/uploads', (req,res) => { upload(req, res, (err) => ...

Why does the Leaflet map appear inconsistently?

It's baffling that Firefox 24.0 and the latest Chrome are both failing to load my Leaflet map, but surprisingly, it works perfectly on Safari on my iPhone. Quite an interesting dilemma. This is my initial attempt at using Leaflet and Bootstrap...ever ...

What can be done to ensure that two separate react-native Picker components do not interfere with each other's

Encountering an issue with two Pickers in a react-native View. Whenever I select a value in one Picker, it causes the other Picker to revert back to its initial item in the list. It seems like the onValueChange function is being triggered for both Pickers ...

Methods for incorporating JSON Data into ChartJS

Below is my app.js file: app.js var app = angular.module('myApp', []); app.controller('MainCtrl', function($scope, $http) { $http.get('http://happyshappy.13llama.com/wp- json/llama/v1/stats').then(function(response) ...