gpt4 book ai didi

angular - 如何在循环中以 Angular 实现多个顺序 Http 请求(每个新请求都取决于以前的结果)

转载 作者:行者123 更新时间:2023-12-05 05:06:36 25 4
gpt4 key购买 nike


我有一个包含要加载的大量数据的网格,因此加载时间变得难以管理。我找到的解决方案是执行连续数量的 http 请求,每个请求批量检索 100 行,直到完成网格上的所有数据。我知道如何使用 concatMap 实现 2 个连续的 http 请求,它工作得很好,但我想有一个 while 循环来验证每个响应,如果当前行数 < 总行数,则订阅一个新的 Http 请求。很奇怪我没有找到任何解决方案,也许我从一开始就认为这个解决方案是错误的:D非常欢迎任何帮助!提前致谢!

用于使用 concatMap 执行 2 个 http 请求的转发代码:

private LoadGridStringResourcesInProject(projectId: number) {
let allData: StringResource[] = [];
const batchSize = 100;

this.stringResourcesService.getStringResourcesInProject(projectId, 0, batchSize)
.pipe(
concatMap(firstData => {
const stringResourcesInProject = firstData as StringResource[];

// Loads first 100 rows on the Grid
this.gridApi.updateRowData({ add: stringResourcesInProject });
this.agGridService.refreshSizeColumns(this.agGrid);

// Fetch data returned by partial Http requests
allData = stringResourcesInProject;

if (allData && allData.length == batchSize) {

// Do new Http request to fetch the remaining data
return this.stringResourcesService
.getStringResourcesInProject(projectId, batchSize, 0);
}

return [];
})
).subscribe(data => {
const stringResourcesInProject = data as StringResource[];

// Loads the remaining rows in the Grid
this.gridApi.updateRowData({ add: stringResourcesInProject });

// Fetch data returned by partial Http requests
allData = allData.concat(stringResourcesInProject);
},
error => of(null),
() => {
this.agGridService.refreshSizeColumns(this.agGrid);
});

最佳答案

如@Maxim1992 所说,解决方案是使用 Expand RxJS 运算符以便递归调用!非常感谢@Maxim1992!

更多信息在这里:Example

以下是您也可以使用的代码(希望它能在将来对某人有所帮助):

private LoadGridStringResourcesInProject(projectId: number) {
const batchSize = 1000;
let iteraction = 0;


this.stringResourcesService.getStringResourcesInProject(projectId, false, false, false, 0, batchSize)
.pipe(
expand(partialData => {
if (partialData) {
let partialStringResourcesInProject = partialData as StringResource[];

if (partialStringResourcesInProject.length > batchSize) {

// Loads the remaining rows in the Grid
this.gridApi.updateRowData({ add: partialStringResourcesInProject });

iteraction += 1;

return this.stringResourcesService.getStringResourcesInProject(projectId, false, false, false,
batchSize * (iteraction - 1), batchSize);
}

return EMPTY;
}
})
).subscribe(data => {

//...
},
error => of(null),
() => {
this.agGridService.refreshSizeColumns(this.agGrid);
});

关于angular - 如何在循环中以 Angular 实现多个顺序 Http 请求(每个新请求都取决于以前的结果),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59767976/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com