簡體   English   中英

想要使用 angular/Ionic 中的 forkJoin 以批處理格式調用多個 api 調用

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM