Vee*_*ota 4 rxjs angular-http angular
如何在 angular 2 中进行并行调用 HTTP get 或 post 调用?
我对一个愈伤组织的响应有 2 个服务呼叫必须拨打另一个电话。
有人可以建议我如何使用错误处理方案调用 make 这些并行调用吗?
如果你的服务是Observable基于而不是Promise你可以做的forkJoin。它并行运行所有可观察的序列。
对于 RxJS 版本 < 6
import 'rxjs/add/observable/forkJoin';
Run Code Online (Sandbox Code Playgroud)
确保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
...
});
Run Code Online (Sandbox Code Playgroud)
或者,如果您希望它是连续的,请进行第一次调用,然后进行完整的调用。
myService.getCall().subscribe((response) => {
// handle response
}, (error) => {
// handle error here
}, () => {
// this is complete block and it is triggered when obervable is complete
myService.postCall();
}
Run Code Online (Sandbox Code Playgroud)
编辑: 对于 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')
);
}
}
Run Code Online (Sandbox Code Playgroud)
成分:
firstResponse: any;
secondResponse: any;
constructor(private myService: MyService) {
}
myFunction(): void {
this.myService.getAndPost().subscribe((res) => {
this.firstResponse = res[0],
this.secondResponse = res[1]
});
}
Run Code Online (Sandbox Code Playgroud)