![](/img/trans.png)
[英]How to make multiple HTTP calls in Angular6, using forkJoin and ngrx?
[英]Want to call multiple api calls in batch format using forkJoin in angular/Ionic
我有一系列请求,例如:
let array = [req1,req2,req3.....,req(n)]
目前,我仅在获得所有请求响应后才使用 forkJoin 调用订阅者。 现在我想修改我的代码以批量进行 api 呼叫,但只有在完成所有批次响应后才能呼叫订户,这可能吗?
例子
public demoCalls() {
let demoForkJoin
var a = [req1,req2,....,req45]
a.map((data,index)=>{
demoFrokJoin[index] = this.http.post()
})
forkJoin(demoForkJoin)
}
现在,我想批量调用 10-10 req 而不是这个。 每 10 个请求将在 1000 毫秒后调用
只有在获得所有 API 的响应后,才会调用一个订阅者。 (所有 45 个 API)
demoCall().subscribe(res=>{
// this subscribe only once after all calls are completed and got success result
})
我建议不要使用批处理,而是使用一些 rxjs 运算符的并发值。 例如, mergeMap
提供了这个值。 完成一个 observable 后,下一个 observable 将被订阅。 为完成操作添加finalize
。
以下示例有 2 个并发请求
import { Observable, of, range } from 'rxjs';
import { delay, finalize, mergeMap } from 'rxjs/operators';
function req(id: number): Observable<number> {
console.log('request received for id', id);
return of(id).pipe(delay(5000));
}
range(0, 10)
.pipe(
mergeMap((r) => req(r), 2),
finalize(() => console.log('all requests done'))
)
.subscribe((id) => console.log('request completed for id', id));
在 Stackblitz 上查看此操作: https://stackblitz.com/edit/typescript-cmylca?file=index.ts
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.