Angular RXJS – Wie man HTTP-Requests in einer Schleife ausführt und für jede Anfrage den Status erhält
In diesem Snippet zeigen wir, wir man für jedes Item eines Arrays einen HTTP-Request feuern und den Status auswerten kann.
Dafür gibt es zwei Möglichkeiten. Mann kann entweder parallele Requests (gleichzeitig) oder sequenzielle Requests (hintereinander) feuern.
Parallele Requests
import { forkJoin, of, from } from 'rxjs';
import { tap, catchError, concatMap } from 'rxjs/operators';
postParallel() {
let success = 0;
let errors = 0;
const requests = this.dataArray.map(item =>
this.http.post(this.url, item).pipe(
tap(x => success++),
catchError(err => {
errors++;
return of(err);
})
)
);
forkJoin(requests).subscribe(
null,
err => console.log(err),
() => console.log(`Success: ${success}\nErrors: ${errors}`),
);
}
Sequenzielle Requests
import { forkJoin, of, from } from 'rxjs';
import { tap, catchError, concatMap } from 'rxjs/operators';
postSequential() {
let success = 0;
let errors = 0;
from(this.dataArray).pipe(
concatMap(item => {
return this.http.post(this.url, item).pipe(
tap(x => success++),
catchError(err => {
errors++;
return of(err);
})
)
})
).subscribe(
null,
err => console.log(err),
() => console.log(`Success: ${success}\nErrors: ${errors}`),
);
}
Ich hoffe wie immer, diese erstbeste Lösung war hilfreich.
