问题描述: 在Angular 7中,使用RxJs进行HTTP调用时,无法在ForkJoin中完成调用。
解决方法:
import { Observable, forkJoin } from 'rxjs';
import { map } from 'rxjs/operators';
const httpCall1$ = this.http.get('url1');
const httpCall2$ = this.http.get('url2');
const httpCall3$ = this.http.get('url3');
const httpCalls$ = [httpCall1$, httpCall2$, httpCall3$];
forkJoin(httpCalls$).subscribe(results => {
// 在这里处理HTTP调用的结果
const result1 = results[0];
const result2 = results[1];
const result3 = results[2];
}, error => {
// 处理错误
});
注意事项:
forkJoin(httpCalls$).pipe(
map(results => {
const transformedResult1 = transformFunction1(results[0]);
const transformedResult2 = transformFunction2(results[1]);
const transformedResult3 = transformFunction3(results[2]);
return [transformedResult1, transformedResult2, transformedResult3];
})
).subscribe(transformedResults => {
// 处理转换后的结果
}, error => {
// 处理错误
});
上一篇:Angular 7 Rxjs - 订阅时尚未取消的正在进行中的HTTP请求
下一篇:Angular 7 RXjs 6.x - 如何使用forkJoin(`of`和`Observable.create`之间的区别)