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

Exploring Query Parameters in Angular 4

Is it possible to generate a custom URL in Angular 4? For instance: http://localhost:4200/#/page/page2/6/abc/1234 Currently, I am utilizing query parameters like this: this.router.navigate(['page/page2/' + row.id],{ queryParams: {'name&a ...

Retrieving a specific variable from a cookie value that is stored within a JSON array

Is there a way to pass a single variable from a JSON array stored in the qookie file value to JavaScript? The qookie code looks like this: <?php $cookie_key = 'count'; CookieManager::store($cookie_key, json_encode(array( 'SameSite&ap ...

Java REST service remains out of reach for JavaScript fetch call

Currently, I am in the process of learning about REST API. My goal is to make a call to a POST service implemented in Java from Javascript using fetch. However, I have encountered an issue where the request fails to reach the service whenever the @Produces ...

Unable to display an image prior to its upload

I'm facing an issue with changing the image for my second data. It's not updating, but when I try it with the first data, it works fine. I'm unsure why this is happening and would appreciate any help in resolving it. Here is the form where ...

An issue arises even with the proper configuration in place: "SessionNotCreatedError: session cannot be established as Chrome version needs to fall within the range of 70 to 73."

During my automated testing with selenium-webdriver, I encountered an issue while building a driver using chromedriver. Everything was functioning perfectly until one day, when I ran a test and received the following error message: SessionNotCreatedErro ...

Utilizing a JSON file for long-term storage of a compact database in JavaScript

As a newcomer to JSON, I wanted my webpage to display a small database of records in a table without using a traditional database like MySQL. Instead, I decided to read data from and write it out to a JSON file for convenient and persistent storage on my w ...

Manipulating Data in TypeScript: Creating a Mutated Copy of a List of Dictionaries

After going through multiple answers, it appears that there might be a logical error. However, I am struggling to find a solution for this issue. In TypeScript/JavaScript, I have two lists of dictionaries. One list is a copy of the other for tracking purp ...

What is the correct way to utilize "data:" in a jQuery AJAX call?

There seems to be an issue with my code within the deletePost function. The problem lies in the fact that $_GET['title'] is empty. Although I set the title value in the ajax using postTitle: $(this).siblings("h3.blog").text(), it doesn't see ...

Writing a CSV file to AWS S3 proves to be unsuccessful

I have been working with TypeScript code that successfully writes a CSV file to AWS S3 when running locally. However, I have recently encountered an error message: s3 upload error unsupported body payload object NOTES: The code is not passing creden ...

Leveraging Sessions in Angular with Spring Boot

As I try to implement a login and session management system for my library portal, I have developed backend services using Spring Boot and frontend with Angular. While exploring an example of Spring Boot + Session Management on this link: , I made some adj ...

Error encountered by React context: TypeError - Attempting to iterate over an object that is not iterable (unable to access property

I'm encountering this error: TypeError: object is not iterable (cannot read property Symbol(Symbol.iterator)) whenever I attempt to handle state using useContext. The purpose here is to initialize "tokens" as an empty array [] on page load, and then ...

What is the best way to prevent the onClick event from triggering during the page rendering process?

I am currently working with React, Gatsby, and Material UI Buttons. I'm facing an issue where the most recently pressed button is getting disabled along with all other buttons when running my code. Despite already implementing bindings, as suggested b ...

Formatting dates in a C# MVC application after parsing JSON

I am working on an MVC application that retrieves data from a SQL database and passes it to a view. One of the views contains a Kendo grid that displays the data, including a date column. The date data is stored in the SQL database as DateTime, while the m ...

A guide on extracting the current website URL in a React application

I wanted to find a method to duplicate the text from a URL so that users could easily share the link with others. ...

Issue arises when compiling React Redux due to a union type that includes undefined

I am currently in the process of learning how to integrate Redux with React using Typescript. I encountered a compilation error that relates to the type of my store's state, specifically as {posts: PostType[]}. The error message states: Type '{ p ...

Click on a div in AngularJS to be directed to a specific URL

I'm currently working on developing an Angular mobile app and I want to be able to navigate to a specific URL, like www.google.com, when a particular div is clicked. Unfortunately, I'm still new to the world of Angular and struggling to achieve t ...

How come TypeScript tuples support the array.push method?

In the TypeScript code snippet below, I have specified the role to be of Tuple type, meaning only 2 values of a specified type should be allowed in the role array. Despite this, I am still able to push a new item into the array. Why is the TS compiler not ...

Having trouble retrieving prices using an npm package

There is a more effective way to retrieve prices using the npm package, node-binance-api, rather than relying on the "coin" variable that I am currently struggling with. If anyone could assist me in finding a better solution or the optimal method for fetch ...

Using AngularJS to pass the output of a unique filter to another custom filter

I have successfully developed two custom filters and am attempting to utilize them both within an ng-repeat loop. Is there a way for me to pass the output of the first filter as an input for the second one? I attempted using 'as' keyword in ng- ...

Achieving JSX rendering in Vue.js with TypeScript starting from a basic CLI setup along with the JSX package integration

The Setup I have set up a new project using the vue-cli, where I manually selected certain features including Babel, TypeScript, Vuex, and Linter / Formatter. Additionally, I chose version 2.x and opted to use Babel alongside TypeScript for modern mode an ...