"Can anyone provide insights on how to retrieve the URL within the .success function of the $http.get function in Angular

Here is the code snippet of my controller:

var app = angular.module('callapp', []);
app.controller('eController', function($scope, $http, $log) {
    $scope.urlString = []; //these values are populated

    for( var i=0; i<3; ++i)
    {
        var currentURL = $scope.urlString[i];
        $http.get(currentURL)
        .success( function(response) {
            //how can I access currentURL here?
            $log.info(this.currURL) //this prints "undefined"
        });
    }

The URLs are dynamically generated before the loop executes. Data needs to be fetched from these URLs which are sent as asynchronous requests.

I attempted using $.ajax(currentURL) instead of $http.get method, but encountered the same issue - "undefined".

Is there a possible way to access both the currentURL and the 'i' value inside the .success(function ())?

Answer №1

currentUrl is easily accessible, and when performing AJAX requests within a for loop, the last index value i will always be retrieved because the renderer prints the value after receiving a 200 response from the AJAX request. This can create a timing issue where the for loop has already completed by the time the value is printed, resulting in the last index being stored in i. To address this issue, an IIFE should be utilized.

For demonstration purposes, a Fake Online REST API - http://jsonplaceholder.typicode.com/ - is being used.

RUNNING DEMO: http://plnkr.co/edit/djPMu4UH9t9BeGwBcUMI

HTML:

<body ng-app="callapp" ng-controller="eController">
</body>

JS:

var app = angular.module('callapp', []);
app.controller('eController', function($scope, $http, $log) {
    $scope.baseUrl = "http://jsonplaceholder.typicode.com/posts/";
    $scope.urlString = [
      $scope.baseUrl + '1',
      $scope.baseUrl +'2',
      $scope.baseUrl + '3'
    ]; //this is filled with values


    for( var i=0; i<3; ++i) {
       (function(index) {
        var currentURL = $scope.urlString[i];
        $http.get(currentURL)
        .success( function(response) {
            $log.info(index+1, currentURL);
        });
      })(i);
    }
});

app.$inject = ['$scope', '$http', '$log'];

Answer №2

You have the option to set up an HttpInterceptor, which allows you to manage and intercept all requests.

For more information, visit: https://docs.angularjs.org/api/ng/service/$http#interceptors

$provide.factory('myHttpInterceptor', function($q) {
  return {
     // optional method
     'request': function(config) {
       // This is your URL:
       console.log(config.url);
       return config;
     },
  };
});

Remember to add the httpInterceptor by using this code snippet:

$httpProvider.interceptors.push('myHttpInterceptor');

Answer №3

Assign the value to a $scope variable since this.currUrl is not defined

 var app = angular.module('callapp', []);
    app.controller('eController', function($scope, $http, $log) {
        $scope.urlString = []; //contains values

        for( var i=0; i<3; ++i)
        {
            $scope.currentURL = $scope.urlString[i];
            $http.get($scope.currentURL)
            .success( function(response) {
                //How can I retrieve currentURL here?

            });
 $log.info($scope.currentURL);
        }

Answer №4

Instead of using a traditional for loop, consider utilizing the angular forEach method. To learn more about angularForEach, please refer to this link.

var app = angular.module('callapp', []);
app.controller('eController', function($scope, $http, $log) {
$scope.baseUrl = "http://jsonplaceholder.typicode.com/posts/";
$scope.urlString = [$scope.baseUrl + '1', $scope.baseUrl +'2',$scope.baseUrl + '3']; //This array is populated

angular.forEach($scope.urlString,function(value,key){

    $http.get(value)
    .success( function(response) {
        $log.info(value) 
    });
}    
});

app.$inject = ['$scope', '$http', '$log'];

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

Having trouble retrieving values from JSON properties

My mind is boggled by this issue, and I have a feeling it's just a simple oversight! I'm dealing with a service that sends back a JSON object: [{"accountId":"0000004000006195","title":null,"firstName":"JOE","middleName":"BLOG","lastName":"BLOGG ...

Understanding the significance of underscores in JavaScript strings

Some places mention using _() around strings like _('some string'). For instance, in a desktop program with these imports: const Applet = imports.ui.applet; const St = imports.gi.St; const Gdk = imports.gi.Gdk; const Gtk = imports.gi.Gtk; const ...

Exciting method for transferring URL parameters in AngularJS

$http({method: 'GET', url: '/asas/asasa'}).success(function(data) { $scope.website = data.websites; $scope.topoffer = data.coupons; $scope.webcall = function () { $http({method: 'GET',url: &a ...

In what way are these columns altering their layout without the use of JavaScript?

While I was searching for a solution to organize content based on screen size, I came across this website. The layout of the site changes depending on the size of the browser window. When I resize my browser or view the site on a phone, the large image at ...

Utilize Angular data binding to assign a class

Within my array, there is an element that holds a value of true or false. This value guides the display logic in this example: <div ng-show="{{ item.isDirectory }}"> Moreover, I seek to implement a similar condition for adding a CSS class to the ...

Ways to extract values from a JSON output using comparisons

I am dealing with a JSON data structure that contains information about various teams. My task is to compare the values in the teams array with the values stored in html_content.position[i]. In this comparison, the index i needs to be dynamically set withi ...

Obtain custom parameter data from a string

Searching for custom parameter values within a string is necessary. For instance, given the following string: aaa[111] bbb[222] ccc[333] ddd[444] I am looking to extract the value 111 associated with the parameter aaa, and so on... The specific paramete ...

Iterating through a collection of objects, triggering a promise for each object and recording its completion

I have encountered a challenge where I need to iterate through an array of objects obtained from a promise, and for each object in the array, I must invoke another promise. After all these promises are executed, I want to display "DONE" on the console. Is ...

JavaScript code utilizing Selenium to retrieve text from a Tinymce text editor

When using https://ocr.sanskritdictionary.com/ to upload an image, the copyable text appears in a Tinymce editor. I am looking for suggestions on how to copy the resulting text using Selenium JavaScript code. I have attempted to extract it using the html ...

The compatibility issue with Internet Explorer and Arabic text is impeding the functionality of jQuery AJAX

$('#search_text').keyup(function() { var search_text = document.getElementById('search_text').value; $.ajax({ url:"jx_displayautocompletelist.php", data: 'text='+search_text, success:function(result){ $ ...

Dealing with 404 errors encountered when making requests to external websites, utilizing either basic Javascript or JQuery

I have links in my application that redirect to external websites. For example, a link might look like this: <http://www.google.com'>>General Search<>. Users input the href and we dynamically create the link without any validation of it ...

Leveraging three.js for visualizing temporal data series

What is the best approach for using time series data to control the animation of a three.js scene? For instance: Time | ObjA(x,y,z) | ObjB(x,y,z) | ... 00:00:00 | 0,9,0 | 1,1,1 | ... 00:00:10 | 0.1,0,0.1 | 1,0.5,1 | ... 00:0 ...

Error message for empty input is not being displayed upon submission in Bootstrap validation

I've been attempting to implement Bootstrap validation in a form with the following desired outcome: Upon submission of the form, if the "First name" field is left empty, a message saying "Please enter a name" should appear below the field. If the f ...

Browser freezes unexpectedly every 10-15 minutes

I have an application that displays 10 charts using dygraphs to monitor data. The charts are updated by sending ajax requests to 4 different servlets every 5 seconds. However, after approximately 10-15 minutes, my browser crashes with the "aw! snap" messag ...

Differences Between JavaScript Binding and Anonymous Functions

I came across this code in the mongoose-deep-populate library async.parallel([ User.create.bind(User, {_id: 1, manager: 2, mainPage: 1}), Comment.create.bind(Comment, {_id: 3, user: 1}), ... ], cb) which utilizes Function.prototype.bind to make ...

Shuffle the JSON data before displaying it

Just a heads up, the code you're about to see might make you cringe, but I'm doing my best with what I know. I've got a JSON file with a bunch of questions, here's what it looks like: { "questions": [ { "id": 1 ...

Retrieving document attributes from a Mongoose Model with the help of Typescript

Incorporating Typescript with Mongoose, my aim is to retrieve properties from a Model. Taking the illustrated UserModel as an example import mongoose, { Schema } from 'mongoose'; const userSchema: Schema = new mongoose.Schema({ _id: mongoos ...

Attempting to activate an ASP button that is created within a gridview after pressing the enter key within a textbox

I am currently working on a gridview with dynamically generated rows, each row containing text boxes and buttons. The goal is to update the database with values from the textboxes when UpdateBtn1 is clicked. Users should be able to either click the button ...

Animating the scaling of a background image with JavaScript resulted in a jittery, unstable image

I'm encountering a shaking effect when I animate a DIV container with a background image using JS. How can I make the animation smoother? $('body').on('click', '#container', function() { $("#container").animate({ ...

Uploading files with Ajax in PHP

Illustration of my Ajax script: Script <script type="text/javascript> $(document).ready(function(){ $('.costExcel').on("submit",function(event){ event.preventDefault() var url = "ajax.php"; ...