Reputation: 31
I want to show the spinner when I click on the button, and hide it when I get all of the data, but I can't figure out how to use async/await in the given example.
This is the simplified version of my code:
.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>
Upvotes: 1
Views: 2062
Reputation: 15566
You have to do it with forkJoin, the below code is just a rough code to portray 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;
})
Upvotes: 0
Reputation: 4294
You can use forkJoin
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/observable/forkJoin';
onLoad() {
this.isLoading = true;
this.http.post(this.Aurl).subscribe(Aresponse => {
this.Aitems = Aresponse;
let observableBatch = [];
this.Aitems.forEach((Aitem, Aindex) => {
let Bbody = Aitem.id;
observableBatch.push(this.http.post(this.Burl, Bbody).subscribe(Bresponse => {
let Bitem = Bresponse;
this.Bitems[Aindex] = Bitem;
}));
});
Observable.forkJoin(observableBatch).subscribe(res => this.isLoading = false;);
});
}
Hope it will solve your issue.
Upvotes: 1