2


我有一个网格,其中包含要加载的大量数据,因此加载时间变得难以管理。我找到的解决方案是执行连续数量的 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);
      });

}

4

1 回答 1

1

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

此处提供更多信息:示例

这是您也可以使用的代码(希望它可以帮助将来的人):

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);
  });
于 2020-01-16T14:54:26.423 回答