Angular中数组分批串行HTTP请求实现方案求助
Angular串行批量POST请求实现方案
需求说明
我是Angular新手,需要实现以下功能:
- 将数字数组拆分为指定大小的批次
- 按顺序串行发起POST请求,仅当前请求成功完成后才发起下一个
- 一旦收到错误响应,立即终止后续所有请求
- 每个请求发送整批数据
初始尝试思路
一开始我用循环拆分数组,但不知道如何等待请求完成再继续执行循环:
const chunkSize = 10; for (let i = 0; i < array.length; i += chunkSize) { const chunk = array.slice(i, i + chunkSize); dataservice.postData(chunk) // 发起HTTP请求 // 不知道怎么等待请求完成再继续循环 }
我认为使用RxJS可以实现更优雅的解决方案。
相关服务代码
调用流程:Component → 数据服务 → API服务(统一处理HTTP请求)→ 服务器
数据服务中的请求方法:
postData(Ids: number[]): Observable<WebApiResponse<boolean>> { return this.ApiService.post(route, endpoint, Ids); }
API服务负责实际发起HTTP请求,服务器接口返回类型为void。
RxJS最终实现代码
最终我采用RxJS实现了需求,代码如下:
const ids$ = from(this.Ids); // 将ID列表转换为Observable this.subscription = ids$.pipe( takeWhile(() => this.isExecuting), bufferCount(this.batchSize), // 按指定批次大小拆分数组 concatMap((batch) => { // 串行处理每个批次的请求 return this.DataService.validate(<object>{ Ids: batch }).pipe( takeWhile((result) => { // 请求成功且未终止时继续 return result.Status === WebApiResponseStatus.Success && this.isExecuting; }), tap(() => { // 更新完成进度 this.completed += batch.length; this.completedPercentage = this.completed / this.totalCount * 100; if (this.completed >= this.totalCount) { this.isExecuting = false; } }) ); }) ).subscribe({ error: () => { // 请求出错时终止后续操作 this.isExecuting = false; this.error = true; } });
内容的提问来源于stack exchange,提问作者Muhammad Motala
相关产品推荐
相关产品推荐

