Steps for sending a value to an AngularJS $http success function

I have a question that is very much like the one posed here: How to pass a value to an AngularJS $http success callback

As per Angular.js

The $http legacy promise methods success and error have been deprecated. You should use the standard then method instead.

So, how can one achieve a similar outcome using .then?

In my service, my code is a bit fragmented, like this:

fetchFromAPI: function(key) {
    return $http.jsonp(...); 
}

And in my controller, I have something like this:

for (var i = 0; i < units.length; i++){
    Service.fetchFromAPI(i)
    .then(function(response) {
        console.log(i);
    }, function(response) {
        console.log(response);
    });
}

However, the console output shows the same number for all iterations due to the for-loop completing before any responses are received. I am struggling to figure out how to achieve a similar result to the .success example without encountering an error stating that my controller is not a function.

The solution offered by Jim Horng is as follows:

$http.get('/plugin/' + key + '/js').success((function(key) {
     return function(data) {
        console.log(key, data);
    }
})(key));

Answer №1

To efficiently iterate through an array in Angular, simply utilize the built-in angular.forEach function.

angular.forEach(units, function(unit, index){
    Service.fetchFromAPI(unit)
    .then(function(response) {
        console.log(unit, response);
    }, function(response) {
        console.log(response);
    });
}

For more information, refer to the official documentation.

Answer №2

Here is an efficient approach:

for (let index = 0; index < elements.length; index++){
  fetchService(index)
  .then((function(count) {
    return function (result) {
      console.log(count, result);
    };
  })(index), function(result) {
    console.log(result);
  });
}

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

Universal access to a constant across every module

Is there a way to create a constant that can be accessed from other modules in AngularJS? I attempted the following code but encountered an exception. How can I modify it to resolve this issue? angular.module('starter', ['starter.Authentica ...

Using Angular 1.5 to trigger a function from the parent controller within a component

Angular 1.5 components make it easy to create a callback from the component to the parent. Is there a way to call a function in a component from a function in the parent's controller? Let's assume that my component is named task-runner and below ...

Enhance the efficiency of React code by optimizing the loading of data from multiple sources concurrently instead of one after another

In my project, there are 2 tabs displaying visualizations generated from separate data sources. Each tab requires multiple queries to be executed in the background to fetch the data, resulting in a delay when loading each tab individually. The current impl ...

Whenever I hover over a dropdown menu item, it suddenly stops functioning and I am forced to click in

I am facing an issue with my responsive dropdown menu that has 4 buttons, one of which opens a submenu (portfolio). The problem occurs when I accidentally click the 'portfolio' button, although it should only be triggered by a hover function. Thi ...

The handler provided to Boost::asio::async_read_until is never triggered

I am attempting to establish a connection between two computers on a local network. One is using a slightly modified version of the Boost Asio C++ TCP asynchronous server sample, while the other is running NodeJS. tcp_client.js : var net = require(' ...

Using Vue Js to bind two values to an href attribute in a tag

As a Vue.js beginner, I am encountering an issue where I need to update two values simultaneously during rendering. <ul class="category-list"> <li v-for="category in categories"> <a v-bind:href="location/category.slug/all" v-tex ...

How can AngularJS handle multiple views sharing the same controller and ensure that the controller is executed only once?

Currently, I am facing a situation where I have two separate views that I would like to control within a single controller. The issue is, the controller is being executed twice. Is there a way to link multiple views to the same controller without the cont ...

Unable to assign a value to a null property during the onchange event

I'm currently working on a project where I need to display flight details based on the selected flight number. To achieve this, I have created a dropdown menu that lists all available flight numbers and a table displaying various flight details such a ...

Swap out original source files in HTML with minified versions

I have successfully utilized a maven plugin to create a minified and compressed version of my CSS and JavaScript files. Now, I am looking to update the section in my main HTML page that currently loads all those individual files. Here is what it looks lik ...

What is the reason behind not being able to assign identical names to my SailsJS models and MySQL tables?

Recently diving into Sails JS, I found myself in unfamiliar territory with RESTful APIs. Following the guide, I created a User model to correspond with my existing users table. Adding attributes based on the table's columns was straightforward, and a ...

When querying a MongoDB object in Node.js, the inner value may sometimes return as undefined

After retrieving a store object from MongoDB, my focus shifted to utilizing the value stored in store.comments. Upon logging the store value, here is what I found: store:{ _id: 57e246f73e63d635cce3d174, __v: 0, comments: 57e246f73e63d635cce3d177, l ...

Using ng-style to apply a background image with a dynamic id

Hey there, I'm facing an issue here. The link provided below seems to not be working properly. Even though the id is set correctly within the scope, it seems like there might be a parsing error occurring. Any thoughts on what might be causing this pro ...

What is the best way to create a slideshow that automatically starts upon loading and pauses when hovered over?

I have recently set up a div element for my slideshow. I've included a script to enable navigation using next and previous arrows. However, I am looking to add an automatic slideshow feature that stops on hover. As a beginner, I would appreciate any a ...

Is there a way to condense my child table directly below its parent column?

When attempting to collapse the "child tr" within the "tr" in my code, the collapse is not positioning correctly underneath its parent tr. While it works fine in a JSFiddle, the issue arises when using my editor and live preview. In this scenario, both "ch ...

Button in HTML not functioning as expected

I have 3 different files that are crucial for my webpage to function properly: index.html: <html> <head> </head> <body> <h1>Webpage</h1> <p id = "text">Hello world!</p> <button oncl ...

What is the mechanism behind JSON.parse()?

As I delve into the realm of using JavaScript to parse an object retrieved from a PHP file, a snippet of pertinent code catches my attention: var name = document.getElementBId("name").value; var XHR = new XMLHttpRequest(); XHR.open("GET', 'looku ...

Creating a function that writes to a file by utilizing the data input from

After running the provided code snippet, it successfully works in a standalone project. However, I am interested in making modifications to replace the variable "sample_text" with an output that is displayed in the terminal instead of being hardcoded int ...

AngularJS reloads the ng:view component

As I work on incorporating my membership system using Angularjs v0.9 and PHP, a crucial function involves calling an API to modify member data. Upon successful execution, the PHP function will respond with {"success":"true"} Following this, the controlle ...

Creating a diverse layout by dynamically adding divs without achieving uniformity in the grid

I'm working on dynamically generating a grid of divs with a specific size using the code below: function createGrid(gridSize) { var container = document.getElementById('container'); for (var i = 0; i < gridSize; i++) { va ...

What exactly is the functionality of the `require('atom')` method?

Atom provides various global APIs that can be easily accessed through require('atom') How does this mechanism function? Despite not being a declared dependency, Atom packages are able to utilize these global APIs. Additionally, is it possible to ...