Async/Await forEach Angular 5 HttpClient



我想在单击按钮时显示微调器,并在获取所有数据时将其隐藏,但我无法弄清楚如何在给定的示例中使用 async/await。

这是我代码的简化版本:

.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>

你可以使用 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;);
});
}

希望它能解决您的问题。

你必须用forkJoin来做,下面的代码只是一个粗略的代码来描绘这个概念。

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;
        })

最新更新