如何处理 angular 上的多个 post 请求?

How to handle multiple post request on angular?

我正在使用 Angular 12 和 NestJS,我需要在同步过程中插入大约 3000 个项目,我从外部 API 获取这些项目并在我的应用程序中注册或更新它们数据库。当我尝试提交请求时,我遇到了很多问题,例如内存使用率高、浏览器冻结,并且 Chrome 中出现 ERR_INSUFFICIENT_RESOURCES 错误并且只有一个输入的项目很少。

我的组件:

this.items.forEach((item) => {
  this.itemService.insert(item).subscribe((res) => {
     console.log(res);
  })
})

我的服务:

insert(item: Item): Observable<Item> {
return this.http.post<Item>(`${APIURL}/item`);
}

我尝试使用 forkJoin,但遇到了同样的问题。我的目标是在没有崩溃的情况下插入或更新项目,并且如果可能的话跟踪进度,例如“3000 个同步中的 500 个...”

根本原因来自 Javascript 异步,这意味着您几乎同时推送 3000 个项目然后 Chrome 将抛出此错误。

要解决此问题,我们应该通过以下解决方案减少请求金额:

为了简单起见,我使用了解决方案 1,它没有解决方案 2 有效,但更简单。

解决方案 1:在 RxJs 中使用 concatMap 等待每个请求完成,如下例所示

import { from, of } from 'rxjs';
import { concatMap, delay } from 'rxjs/operators';

const items = [1, 2, 3, 4, 5];

from(items)
  .pipe(concatMap(item => of(item).pipe(delay(1000))))
  .subscribe(console.log);

然后您可以将 of(item).pipe(delay(1000))) 替换为您的 instert(item) post 请求。

现场演示:https://stackblitz.com/edit/typescript-uamv8w?file=index.ts