Exploring the power of Async/Await with Angular 5 HttpClient and forEach

I am struggling to implement async/await in my code to show a spinner when I click on a button and hide it once I have all the data. Below is a simplified version of what I have:

.ts:

isLoading: boolean = false;

onLoad() {
    this.isLoading = true;
    this.http.post(this.Aurl).subscribe(Aresponse => {
        this.Aitems = Aresponse;
        this.Aitems.forEach((Aitem, Aindex) => {
            let Bbody = Aitem.id;
            this.http.post(this.Burl, Bbody).subscribe(Bresponse => {
                let Bitem = Bresponse;
                this.Bitems[Aindex] = Bitem;
            });
        });
    });
    // this.isLoading = false;
}

.html:

<button (click)="onLoad()">Load</button>

<mat-progress-spinner *ngIf="isLoading" mode="indeterminate"></mat-progress-spinner>

<div *ngIf="!isLoading" >  
    <div *ngFor="let Bitem of Bitems">
    </div>
</div>

Answer №1

If you're looking to handle multiple HTTP requests concurrently, consider using forkJoin

import {Observable} from 'rxjs/Observable';
import 'rxjs/add/observable/forkJoin';
onLoad() {
this.loading = true;
this.http.post(this.urlA).subscribe(responseA => {
    this.itemsA = responseA;
    let batch = [];

    this.itemsA.forEach((itemA, indexA) => {
        let bodyB = itemA.id;
        batch.push(this.http.post(this.urlB, bodyB).subscribe(responseB => {
            let itemB = responseB;
            this.itemsB[indexA] = itemB;
        }));
    });
    Observable.forkJoin(batch).subscribe(res => this.loading = false;);
});
}

Hoping this solution helps with your current situation.

Answer №2

To achieve this, you need to utilize forkJoin. The code snippet below serves as a basic illustration of the concept.

this.isLoading = true;
this.http.post(this.Aurl)
    .do(Aresponse => console.log(Aresponse)
    .mergeMap(Aresponse => Observable.forkJoin(Aresponse.map((item, index) => this.http.post(this.Burl, item.id))))
    .subscribe(resultSet => {
        console.log(resultSet); //handle each value emitted here
        this.loading = false;
        })

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

The console date format does not match the input date format

I have successfully configured my date format to yyyy-MM-dd and I want my component to output the date in that specific format. The input field displays dates correctly, such as 2020-10-03, but when I use console.log(), it shows: endDate: Sat Oct 03 2 ...

Issue with Angular 2 (Ionic 2): Struggling to properly display Component within Page

I have successfully created an Angular 2 Component: import {Component, View} from 'angular2/core'; @Component({ selector: 'sidemenu' }) @View({ templateUrl: 'build/pages/menu/menu.html', }) export class Menu { } Howev ...

I am looking to remove identical innerText values from two arrays using JavaScript

Is it possible to use JavaScript to remove the "added" className of an element with the same innerText when the delete button (.btn-wrap>li>button) is clicked? <div class="table"> <ul> <li class="added">l ...

Creating an Angular service that checks if data is available in local storage before calling an API method can be achieved by implementing a

I am currently working on developing an Angular service that can seamlessly switch between making actual API calls and utilizing local storage within a single method invocation. component.ts this.userService.getAllUsers().subscribe(data => { conso ...

Position filter forms on the left side to align with bootstrap cards

I'm having trouble aligning the cards using Bootstrap's row and col- classes. The first three are behaving as expected, but the fourth one isn't cooperating. Any idea why this might be happening and any solutions you can suggest? View the i ...

`AngularJS Voice Recognition Solutions`

In my quest to implement voice recognition in an AngularJS application I'm developing for Android and Electron, I've encountered some challenges. While I've already discovered a suitable solution for Android using ng-speech-recognition, fin ...

A guide on utilizing Material UI Fade for smoothly fading in a component when a text field is selected

I am facing an issue with a text field input and a helper component. My goal is to have the helper component fade in when a user focuses on the input field. The helper component is wrapped as follows: <Fade in={checked}> <DynamicHelperText lev ...

Leverage the power of an Angular component for repeated

Attempting to recycle an Angular component within the given tree structure. https://i.sstatic.net/LVvwO.png The desired component, existing-savings, is located in transfer-guide. Trying to utilize this component in retirement-contributions-information. ...

Steps to resolve the issue of 'type is not assignable to any' while working with a member

I'm facing an issue with a code snippet like the one below: interface IFoo { bar: string; baz: number; } function f(foo: IFoo, name: 'bar' | 'baz', val: any) { foo[name] = val; // <<< error: Type 'any' i ...

The member 'email' is not found in the promise type 'KindeUser | null'

I'm currently developing a chat feature that includes PDF document integration, using '@kinde-oss/kinde-auth-nextjs/server' for authentication. When trying to retrieve the 'email' property from the user object obtained through &apo ...

"Import data from a text file and store it as an array of objects using Types

I need assistance with converting the information in my text file into an array of objects. Below is a snippet of the data from the text file: DOCNO NETAMOUNT IREF1 IREF2 DOCDT 001 30000 50 100 6/7/2020 2 40000 40 90 6/7/2020 Currently, t ...

Traverse through an array of objects with unspecified length and undefined key names

Consider the following object arrays: 1. [{id:'1', code:'somecode', desc:'this is the description'}, {...}, {...}] 2. [{fname:'name', lname:'last name', address:'my address', email:'<a h ...

What could be causing my Mongoose controller to not be executed?

I am currently working on developing an API using Mongoose and Express. I have successfully set up several routes that are functioning properly. However, I am facing an issue with a specific route that is intended to search for a model called Subassembly b ...

How can we avoid a runtime error when attempting to filter an array that may not be present at a certain point in

Encountering a runtime error with my reducer state chunk - specifically a TypeError stating that an intermediate value is not iterable. This occurs when the object, childGroup, may not be present in the state at a given moment. Any solutions on how to avoi ...

Struggling to deploy a Typescript React / NestJS application on Heroku due to the error message "error TS2307: Cannot find module"?

Switching from a Typescript React/Express app to using Nest.JS has caused complications when deploying to Heroku. The app runs smoothly locally, but encounters build failures on Heroku. Despite efforts to troubleshoot, it remains unclear whether the issues ...

center a horizontal line using StyledSheets in your project

After drawing a horizontal line, I noticed that it is positioned towards the left side of the screen. I am hesitant to increase its width. Are there any other methods to move it to the center? I attempted wrapping it with another view and using alignConten ...

Lack of Intellisense in Sveltekit for the generated $types module on WebStorm

Is there a setting in WebStorm to enable intellisense for automatically generated ./$types by SvelteKit? I'm writing without any minimal example, just curious. Everything is done according to SvelteKit's documentation. Using satisfies LayoutLoad ...

Setting the type of a prop dynamically based on another prop value

Consider the following scenario with an interface: interface Example { Component: React.ReactElement; componentProperties: typeof Example.Component; } Is there a way to determine the type of properties expected by a passed-in custom component? For ...

The HAProxy is encountering difficulties when trying to connect to port 80 for the Angular application that is currently running on

I currently have an Angular application running on port 4200, and I have implemented HAProxy as a reverse proxy to redirect all traffic from port 80 to 4200. However, while my HAProxy settings are correctly directing traffic from 8080 to 4200, the redire ...

The Ionic tab is already finished displaying even before the data has completed loading

Creating a favorites section for a vouchers app has proven to be slightly challenging. When attempting to retrieve the current user's favorite vouchers and display them using ngFor in the HTML, I encountered an issue. The very first time I open the fa ...