Challenge encountered with asynchronous angular queries

Dealing with asynchronous calls in Angular can be tricky. One common issue is getting an array as undefined due to the asynchronous nature of the calls. How can this be solved?


private fetchData(id){
   var array = [];
   this.httpClient.get('someUrl/'+id).subscribe((organisation)=> {
      console.log(organisation.teams);   // ['team1','team2','team3']
      organisation.teams.forEach((team) => {
          this.httpClient/get('someUrl/'+team).subscribe((teamData) => {
             array.push(teamData);
          })
       })
       console.log(array);    // undefined
    })
}

Answer №1

It seems like your code is functioning correctly, and you are effectively utilizing the subscribe feature. The reason why you are logging undefined is that the line console.log(array) is being executed before the asynchronous get request to 'someUrl'+team returns a value. You can verify this by moving the console.log(array) line inside the scope of the subscription (where you have array.push(teamData)).

An alternative approach, with reduced indentation and a more contemporary style, is to use async/await:

private async fetchData(id){
   var array = [];
   let organisation = await this.httpClient.get('someUrl/'+id).toPromise();
   console.log(organisation.teams);   // ['team1','team2','team3']
   let teamData;
   organisation.teams.forEach(async (team)=>{
       teamData = await this.httpClient/get('someUrl/'+team).toPromise()
       array.push(teamData);
   })
   console.log(array);
}

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

Struggling to uncheck all selected boxes using jQuery

I've attempted various methods, but I'm unable to create code that will uncheck or clear all checkboxes once they have all been selected. Here is the latest version of my code... $(".select_all").click(function(){ var state = ($(this).html( ...

Every time an npm installation is attempted, the following error occurs: "npm ERR! Cannot read property 'resolve' of undefined."

Welcome Everyone! Currently, I am facing an issue on my dual boot system where Node and NPM were functioning smoothly on Windows 7. However, now that Windows 7 is not booting up, presumably due to hardware problems, I have resorted to using Windows 10. E ...

What are the steps to get the Dropdown Button to function in HTML and CSS?

Currently, I am in the process of constructing a website and have set it up so that when the window width is less than 768px, the navbar collapses into a vertical orientation. The issue I am facing is that even though the navbar collapses, the individual i ...

Guide on Validating and Updating an embedded item within a mongoDB Collection Document

How do I go about updating the values of an embedded object within a mongoDB document? The values displayed for {{service.id}} and {{service.username}} in the table template are correct. However, I am unsure of the correct way to access them within the sa ...

Discover the use of dot notation for accessing nested properties

In the deps array below, I aim to enforce type safety. Only strings allowed should be in dot notation of ${moduleX}.${moduleX service} // Modules each have a factory function that can return a services object (async) createModules({ data: { factory: ...

Submit information from an HTML form to a PHP script and then send the response back to the client using AJAX,

Looking to run a PHP script using AJAX or JavaScript from an HTML form and then receive the results on the HTML page. This is what my changepsw.php file looks like: <?php // PHP script for changing a password via the API. $system = $_POST['syst ...

Create a cylindrical HTML5 canvas and place a camera view inside the cylinder

I have a unique project in mind that involves creating an HTML5 canvas cylinder with the camera view at its center. The walls of the cylinder will display images, and the entire structure should be able to rotate and zoom. If anyone has any advice on how ...

Picture failed to load

I am struggling to get an image to display on my webpage, as only the alt text is appearing. Here is the code I am using: return ( <> <div className="container my-5"> <div className="row ju ...

Using VueJS to iterate through an array while applying a condition to filter out certain elements (combining v-for with v-if)

I'm currently working on a v-for loop to display two columns of card elements. The idea is to print the current element and the next one in a row if the index is even, skipping the elements with odd indexes. This is what my code looks like: <temp ...

Is it possible to modify a variable within the readline function?

Can anyone help me figure out how to update the variable x within this function? const readline = require('readline'); const r1 = readline.createInterface({ input: process.stdin, terminal: false }); let x = 1; r1.on('line', fu ...

React component rendering twice due to width awareness

In a React component that I've developed, I have utilized ResizeObserver to track its own width. Within this component, two divs are rendered with each having a "flex: 1" property to ensure equal width distribution. Under certain conditions, such as w ...

Seeking assistance in identifying the highest value in JavaScript (excluding the use of the max method)

Greetings and thank you for stopping by. I'm new to Javascript and currently facing an issue that I could use some help with. I am trying to identify the highest number from a set of variables using conditional statements within a function, but I seem ...

Issue with bidirectional binding on angular material slide toggle not functioning as anticipated (Angular 4)

My angular material slide-toggle implementation seems to be working, but I'm facing an issue where it doesn't bind the value to the relevant variable as expected. // other irrelevant imports above.. import {MatDialog, MatDialogRef, MAT_DIALOG_DA ...

Ways to display an icon upon hovering or clicking, then conceal it when the mouse is moved away or another list item is clicked using ngFor in Angular 7

Within a simple loop, I have created a list with multiple rows. When a row is clicked or hovered over, it becomes active. Subsequently, clicking on another row will deactivate the previous one and activate the new one. So far, everything is functioning c ...

Organizing your project with VueJS, VuelidateJS, and NodeJS/Express for optimal structure

Primarily, I specialize in developing intranet sites and web front-ends for embedded devices using NodeJS. Currently, all my code is contained within one NPM package. I have NodeJS running behind Nginx, allowing Nginx to serve css/image/client-side-javasc ...

Uploading Boolean Values from Switch Input (React/Typescript)

I'm facing an issue while trying to post the state value of a switch input toggle control. Whenever I use the submitRecommendation() function through a button click, I encounter a JSON parse error: Cannot deserialize instance of `boolean` out of START ...

Extracting Ajax data - iterating through each piece of information

I am facing an issue with my ajax code. I have a collection of checkboxes, where the goal is to insert the data from the selected checkboxes into the database. When I choose just one checkbox, the insertion works fine. However, if I select multiple checkb ...

How come modifying the css of one component impacts all the other components?

Issue: I am struggling to make CSS changes only affect the specific component I want, without impacting other elements on the page. My goal is to style my dropdown menu without affecting other text input fields: Background/Challenge: While I understand wh ...

Troubleshooting Issue with Formidable Not Working with Multer

Attempting to develop a webpage that enables users to upload a file to a designated folder while specifying a number in an input field. Currently, I am navigating through the Multer library despite typically using body-parser. Referencing both my app.js an ...

Is it possible to integrate a Twitter bootstrap theme into a Rails 4 application if the Vendor/assets directory is missing?

My goal is to integrate a theme from wrapbootstrap.com into my rails 4.1 application. After creating a new app with rails 4 scaffolding, I proceeded to extract the downloaded zip directory which contains 4 directories and an index.html file. I then placed ...