如何在角2中进行并行调用、HTTP或post调用?
我有两个服务电话,关于一个愈伤组织的反应必须打另一个电话。
有人能建议我如何用错误处理方案调用这些并行调用吗?
发布于 2018-01-17 12:06:21
如果您的服务是基于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();
}编辑: for 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]
});
}https://stackoverflow.com/questions/48300711
复制相似问题