如何进行并行调用HTTP获取或发布角度为2的调用?
我有2个服务呼叫,一个callus的响应必须再拨打一个电话。
有人可以建议我如何使用错误处理方案调用这些并行调用吗?
答案 0 :(得分:4)
如果您的服务基于Observable
而不是Promise
,则可以执行forkJoin
。它并行运行所有可观察序列。
对于RxJS版本< 6
import 'rxjs/add/observable/forkJoin';
确保来自import forkJoin
图书馆的rxjs
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]
});
}