如何在 Angular 2 中进行并行调用 HTTP get 或 post 调用?
我有 2 个服务调用,一个愈伤组织的响应必须进行另一个调用。
有人可以建议我如何在错误处理场景中调用这些并行调用吗?
最佳答案
如果您的服务基于Observable
而不是Promise
,您可以执行forkJoin
。它并行运行所有可观察序列。
对于 RxJS 版本 < 6
import 'rxjs/add/observable/forkJoin';
确保从 rxjs
库中导入 forkJoin
Observable.forkJoin(myService.getCall(),
myService.postCall(),
...)
.subscribe((res) => {
res[0] // this is first service call response,
res[1] // this is second service call response
...
});
或者,如果您希望它是连续的,则执行第一个调用,然后在完成调用时执行第二个。
myService.getCall().subscribe((response) => {
// handle response
}, (error) => {
// handle error here
}, () => {
// this is complete block and it is triggered when obervable is complete
myService.postCall();
}
编辑:对于 RxJS 6 及更高版本,forkJoin
已更改
服务:
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')
);
}
}
组件:
firstResponse: any;
secondResponse: any;
constructor(private myService: MyService) {
}
myFunction(): void {
this.myService.getAndPost().subscribe((res) => {
this.firstResponse = res[0],
this.secondResponse = res[1]
});
}
关于angular - 以 Angular 2 进行并行调用 http get 或 post 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48300711/