问题
How to make parallel calls HTTP get or post calls in angular 2?
I have 2 service calls on the response of one callus have to make another call.
Could some suggest me how to call make these parallel calls with error handling scenarios?
回答1:
If your service is Observable
based instead of Promise
you can do forkJoin
. It runs all observable sequences in parallel.
For RxJS version < 6
import 'rxjs/add/observable/forkJoin';
Make sure to import forkJoin
from rxjs
library
Observable.forkJoin(myService.getCall(),
myService.postCall(),
...)
.subscribe((res) => {
res[0] // this is first service call response,
res[1] // this is second service call response
...
});
Or if you want it to be sequential do the first call and on complete call second.
myService.getCall().subscribe((response) => {
// handle response
}, (error) => {
// handle error here
}, () => {
// this is complete block and it is triggered when obervable is complete
myService.postCall();
}
EDIT: for RxJS 6 and above forkJoin
has changed
Service:
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { forkJoin, Observable } from 'rxjs';
@Injectable()
export class MyService {
constructor(private http: HttpClient) {
}
getAndPost(): Observable<any> {
return forkJoin(
this.http.get('/api/get'),
this.http.post('/api/post')
);
}
}
Component:
firstResponse: any;
secondResponse: any;
constructor(private myService: MyService) {
}
myFunction(): void {
this.myService.getAndPost().subscribe((res) => {
this.firstResponse = res[0],
this.secondResponse = res[1]
});
}
来源:https://stackoverflow.com/questions/48300711/make-parallel-calls-http-get-or-post-calls-in-angular-2