gpt4 book ai didi

angular - 以 Angular 2 进行并行调用 http get 或 post 调用

转载 作者:太空狗 更新时间:2023-10-29 18:19:13 24 4
gpt4 key购买 nike

如何在 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com