Using AngularJS, call the $http function in response to another HTTP request

I recently started working with angular JS and I encountered a problem while trying to implement $http within the response of another $http call.

My problem is that when I make a $http call within the response of another $http call, the data is not displayed on the view. The view gets rendered before the second $http call is made. I tried using promises but without success. Below is the code snippet from another answer that I used with a few modifications.

angular.module('App', [])

.controller('Ctrl', function($scope, resultsFactory) {
  resultsFactory.all().then(
    function(res){
      $scope.results = res;
    },
    function(err){
      console.error(err);
    }
  );
})

.factory('resultsFactory', function($http, $timeout, $q) { 
  var results = {};  

  function _all(){
    var d = $q.defer();
     $http({
       url: url,
       method: 'POST'
     }).then(function (response) {
        var f = {};
        f.id = response.data.id;
        f.name = response.data.name;
        $http({
           url: url,
           data: "id="+response.data.parent_id,
           method: 'POST'
        }).then(function (response1) {
               f.parentname = response1.name;
               d.resolve(f);
        });
     });
    return d.promise;       
  }

  results.all = _all;
  return results;
});

The id and name are displayed correctly on the view, but the parent name is not showing anything. I have debugged it and found that it is undefined when the view is rendered. It sets the value for parentname after the rendering. Can anyone help me resolve this issue?

Answer №1

Instead of using a deferred, you can simply chain the promises together like this:

 return $http({
   url: url,
   method: 'POST'
 }).then(function (response) {
    var data = {};
    data.id = response.data.id;
    data.name = response.data.name;
    return $http({
       url: url,
       data: "id="+response.data.parent_id,
       method: 'POST'
    }).then(function (response1) {
           data.parentname = response1.name;
           return data;
    });
 });

Answer №2

Your d variable was overwritten...

.factory('resultsFactory', function ($http, $timeout, $q) {
    var results = {};

    function _all() {
        var d = $q.defer();
        $http({
            url : url,
            method : 'POST'
        }).then(function (response) {
            var secondD = {};
            secondD.id = response.data.id;
            secondD.name = response.data.name;
            $http({
                url : url,
                data : "id=" + response.data.parent_id,
                method : 'POST'
            }).then(function (response1) {
                secondD.parentname = response1.name;
                secondD.resolve(d);
            });
        });
        return d.promise;
    }

    results.all = _all;
    return results;
});

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

To prevent the background window from being active while the pop-up is open

I have a link on my webpage that triggers a pop-up window, causing the background to turn grey. However, I am still able to click on other links in the background while the pop-up is open. I tried using the code document.getElementById('pagewrapper&ap ...

Sending data when button is clicked from Google Apps Script to sidebar

I have been attempting to pass a list that includes both the start cell and end cell of the active range. I want to then assign each value from this list to separate input fields. document.getElementById("btn-get-range").addEventListener('click&apo ...

Handling Navigation for URLs without Hash in AngularJS

When trying to navigate to URLs with hashes, such as http://www.example.com/#/random, the redirection works properly. But when attempting to access http://www.example.com/random, instead of redirecting, I receive a "Cannot GET /random" error message. Is ...

Adding an arrow to a Material UI popover similar to a Tooltip

Can an Arrow be added to the Popover similar to the one in the ToolTip? https://i.stack.imgur.com/syWfg.png https://i.stack.imgur.com/4vBpC.png Is it possible to include an Arrow in the design of the Popover? ...

Utilize AJAX to accurately capture and handle error codes

Here is a snippet of code that I want to send to my server: $.ajax({ type: 'POST', url: 'post.php', data: { token: '123456', title: 'some title', url: 'http://somedomain.com', data: & ...

hapi-auth-cookie: encounters an issue while trying to read cookies for accessing restricted content

I've implemented hapi-auth-cookie for managing cookies and sessions on my website. Certain parts are restricted and can only be accessed after authentication. When a non-logged-in user tries to access these areas, they are redirected to the login rout ...

Error: The requested resource, youtube#videoListResponse, is currently unavailable

When attempting to access a YouTube playlist that includes private videos, the bot will encounter an error message. Error: unable to locate resource youtube#videoListResponse Below is the code snippet in question: if (url.match(/^https?:\/\/(w ...

Turn on / off Button Using a Different Button

I am currently working on an application that is designed to create teams using button selectors. There are two initial teams in play: the (available team) which consists of two buttons - one for selecting a player and populating the player name into the ( ...

Ways to obtain the chosen option from a drop-down menu using jQuery

I'm currently experiencing an issue where the selected value of a drop down is not being displayed correctly. Instead of selecting the dropdown value, it's adding another value to the list. Below is the code snippet I'm using: JQuery var ...

Why do I keep getting undefined when I use React.useContext()?

I'm currently using Next.js and React, employing react hooks along with context to manage state within my application. Unfortunately, I've encountered a perplexing issue where React.useContext() is returning undefined even though I am certain tha ...

Struggling to synchronize the newly updated Products List array in zustand?

Let me clarify the scenario I am dealing with so you can grasp it better. I have a Cart and various Products. When a user adds the product (product_id = 1) twice to the cart with the same options (red, xl), I increase the quantity of that item. However, i ...

The search filter in Angular is limited in its ability to search through the entire table

I am facing an issue with the search filter in my table. Currently, it only searches records from the current page but I need it to search through the entire table. How can I modify it to achieve this? <input type="text" placeholder="Search By Any..." ...

Tips for triggering several functions with a single onClick event in React?

I am currently working on a React Project where I have defined several functions to set conditions for rendering components on the page. However, I now need to be able to call all these functions again within the components when a button is clicked, in ord ...

Align the content to the right and center it within the table

One common issue I face is working with tables that contain numbers requiring right alignment to ensure the ones/tens/hundreds/thousands places line up correctly. Here's an example: 2,343 1,000,000 43 43,394 232,111 In these tables, ...

Changing the text during a reset process

I've been grappling with this issue, but it seems to slip through my fingers every time. I can't quite put my finger on what's missing. My project involves clicking an image to trigger a translate effect and display a text description. The ...

Using Javascript's Speech Recognition to activate a button

I am new to using JavaScript Speech Recognition and decided to work with the Annyang library. My goal is to automatically trigger the "show date" button when the user says 'hello', without actually clicking the button. However, I've been fac ...

Steps for adding a class to an element in VueJS

https://codepen.io/nuzze/pen/yLBqKMY Here's my issue at hand: I currently have the following list stored in my Vue data: { name: 'Camp Nou', id: 'campNou' }, { name: 'Abran cancha', id: 'abranCancha ...

The application is failing to launch following an upgrade to PostCSS version 8 in a React environment

While working on my app, I discovered that I had 80 vulnerabilities. These vulnerabilities were mainly due to peer version mismatches, such as one package requiring React 16.8.0 while I had 17.0.1. However, there was one vulnerability that caught my attent ...

Eliminate the bottom border from the MUI Input component

Is there a way to get rid of the bottom-line borders on these input fields? I attempted using CSS but couldn't find a solution for this component -> <Input type={"text} /> ? https://i.sstatic.net/4QpWym.png ...

Is it necessary to include my library dependencies in the devDependencies section if I am only planning to publish the library bundle?

When creating a bundle for a library, should the library dependencies be placed in devDependencies? I am developing an NPM library in TypeScript that relies on several dependencies, including React components. As part of the build process, we compile to J ...