Looping through a series of URLs in AngularJS and performing an $

Currently, I am facing an issue while using angular.js with a C# web service. My requirement is to increment ng-repeat item by item in order to display updated data to the user. To achieve this, I attempted to utilize $http.get within a loop to refresh the data for each item. However, I encountered difficulties as it did not work as expected.

for (var i = 0; i < conditions.length; i++) {
        var configFullAsset = {
            params: {
                Field: Field,
                SAM_ConnectionString: SAM_ConnectionString,
                TreeElemId: conditions[i][0],
                ConditionDate: conditions[i][1]
            }
        };
        $http.get('application.asmx/getExtFullAssetHealth', configFullAsset)
            .success(function (responseExt) {
                console.log("Element: ", i);
                if (i == 0) 
                {
                    $scope.showData = responseExt;

                    $scope.fullAssetTable_loading = false;
                    $scope.fullAssetTable_loaded = true;
                }
                else
                    $scope.showData = $scope.showData.concat(responseExt);

                //console.log("Data item: ", $scope.showData[i].Tag);

                $scope.fullData = $scope.showData;
                $scope.filterData(customFilter);
            })
            .catch(function (err) {
                console.log("Error get object: ", err);
            })
            .finally(function () {
                // Hide loading spinner whether our call succeeded or failed.
                //$scope.loading = false;


                $scope.fullData = $scope.showData;
                $scope.filterData(customFilter);
                $scope.fullAssetTable_loading = false;
                $scope.fullAssetTable_loaded = true;

                console.log($scope.fullData);
            });
    }

Answer №1

The issue with your code lies in the following: you are using 'i' as an index in the success method, but it is not behaving as expected because the loop continues until the first success is called.

To make your code more readable, you can construct the requests like this in the initial phase:

function buildRequests() {
    return conditions.map(function(condition) {
        var configFullAsset = {
            params: {
                Field: Field,
                SAM_ConnectionString: SAM_ConnectionString,
                TreeElemId: condition[0],
                ConditionDate: condition[1]
            }
        };

        return $http.get('application.asmx/getExtFullAssetHealth', configFullAsset);
    });
}

You can then handle all the requests in this manner:

function handleRequests() {
    var requests = buildRequests();
    $q.all(requests)
        .then(handleRequests)
        .catch(function(error) {
            console.log(error);
        })
        .finally(function() {
            $scope.fullData = $scope.showData;
            $scope.filterData(customFilter);
            $scope.fullAssetTable_loading = false;
            $scope.fullAssetTable_loaded = true;
        });
}

Next, iterate over each result to make the necessary changes:

function handleResults(results) {
    results.forEach(function(response, i) {
        console.log("Element: ", i);
        if (i == 0) 
        {
            $scope.showData = response;

            $scope.fullAssetTable_loading = false;
            $scope.fullAssetTable_loaded = true;
        }
        else
            $scope.showData = $scope.showData.concat(response);

        //console.log("Data item: ", $scope.showData[i].Tag);

        $scope.fullData = $scope.showData;
        $scope.filterData(customFilter);
    });
}

Remember to inject $q as a dependency injection.

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

Linking a Git repository as a dependency in the package.json file

I have a Git repository that I would like to use as a dependency in the package.json file of another project. This way, it can be easily downloaded when we run the npm command. Can someone please assist me with this? ...

Vue alert: The instance does not have a defined "hp" property or method, but it is referenced during rendering

Below is the code snippet that I am currently working with: var example1; var hp = ["p"]; document.addEventListener("DOMContentLoaded", function(event) { hp = ["x"]; example1 = new Vue({ el: '#example-1', data: { iLoveMysel ...

What is the best way to incorporate real-time push notifications on my website?

My website consists of two main parts. One part is utilized by individuals labeled as X, while the other is reserved for those identified as Y. When a person from group X requests assistance, members of group Y promptly respond with an estimated time of ...

Is it possible to utilize a map in Python or incorporate other advanced functions to efficiently manage indices?

When working with higher order functions in JavaScript, we have the ability to access the element, index, and iterable that the function is being performed on. An example of this would be: [10,20,30].map(function(element, index, array) { return elem + 2 ...

The call to Contentful's getAsset function resulted in an undefined value being

I am facing a challenge while trying to fetch an asset, specifically an image, from Contentful and display it in my Angular application. Despite seeing the images in the Network log, I keep encountering an issue where the console.log outputs undefined. Any ...

Remove the initial section of the text and provide the rest of the string

I am a beginner in the world of Javascript and unfortunately I have not been able to find an answer to my current problem. Here is the situation. On a webpage, I am receiving a URL that is sometimes presented in this format: http://url1.come/http://url2.c ...

Trouble with Bootstrap 5 Dropdown Menu failing to drop down

I am attempting to utilize a dropdown menu on my Wordpress site with Bootstrap, but it is not working as expected. If I manually add the class "show" to my dropdown-menu div, the menu displays, but the button does not function. These are the scripts being ...

Alternative solution to avoid conflicts with variable names in JavaScript, besides using an iframe

I am currently using the Classy library for object-oriented programming in JavaScript. In my code, I have implemented a class that handles canvas operations on a specific DIV element. However, due to some difficulties in certain parts of the code, I had t ...

What is the best way to designate unique custom login redirects based on user type?

I am facing a challenge that I can't seem to overcome. Part of the issue is my struggle to articulate it effectively with the right terminology. As a newcomer in this field, please forgive me for posing such a clumsy question. Below is an outline of ...

Angular UI Bootstrap collapse directive fails to trigger expandDone() function

I am currently utilizing UI Bootstrap for Angular in one of my projects, and I have developed a directive that encapsulates the collapse functionality from UI Bootstrap. Here is how it looks: app.directive( 'arSection', ['$timeout', fu ...

Another option could be to either find a different solution or to pause the loop until the

Is it possible to delay the execution of a "for" loop until a specific condition is met? I have a popup (Alert) that appears within the loop, prompting the user for confirmation with options to Agree or Cancel. However, the loop does not pause for the co ...

Tips for choosing an option in a form using Selenium with JavaScript

I am currently in the process of automating some tests for a specific form, and I have successfully automated all steps except for selecting an option from a dropdown menu using JavaScript. Here is my code: const {Builder, By, Key} = require("sel ...

The public folder in Node.js is known for its tendency to encounter errors

I'm facing an issue with displaying an icon on my website. Here is the current setup in my code: app.js const http = require('http'); const fs = require('fs'); const express = require('express') const path = require(&apo ...

Navigating using angular's UI router - Save for later option

I am working on a project that involves a controller and a view. The view consists of three dynamic drop-down menus and a table. When a value is selected in dropdown1, a REST call is triggered to fetch values for dropdown2. The controller contains the nece ...

Error: Attempting to access the value property of a null object within a React Form is not possible

I am currently developing a form that includes an HTML input field allowing only numbers or letters to be entered. The abbreviated version of my state interface is outlined below: interface State { location: string; startDate: Date; } To initiali ...

Unable to Trigger Virtual Click Event on Calendar in JavaScript

My workplace utilizes a custom web application with a date picker/calendar that I am attempting to modify programmatically. The app is built in Vue, which has added complexity to my task. Despite exhaustive efforts, I have been unable to select or inject d ...

I have decided to integrate Laravel with Vite for building CSS and JS. However, when I attempted to run `npm run dev`, it appeared to execute but was accompanied by an error in the background that

Hi there, I'm new to Laravel and I've created a small app that primarily uses CSS and JS scripts. Everything was working fine in my development environment, so I decided to push it to a production server. However, after installation, my code does ...

Is there a way to retrieve a cell value from a database and use it as the default selection in a dropdown list using AngularJS?

Is there a way to pull a cell value from a database and have it automatically set as the default value in a dropdown list using AngularJS? I am trying to achieve this using the following code: <div class="form-group"> <la ...

The slider customization on Joomla is functioning perfectly on my local machine, but it seems to be encountering some issues on

Having recently started working on a Joomla website for the first time, I encountered some challenges when trying to add a slider module. Despite successfully implementing the slider on my local machine, I faced issues when transferring the code to the liv ...

The angular-block-ui feature fails to run my HTML code as a personalized message

I'm looking to enhance my UI by implementing a blocking feature with a spinner display. My attempt involved the following code: blockUI.start("<div class='dots-loader'>Minions are Working!</div>"); // code for fetching data ...