首页 > 解决方案 > 使用 expand 进行递归调用的分页

问题描述

我从第三方 API 获取数据,这需要我通过跟踪检索到的记录数和记录总数来手动管理分页。

我尝试在 RxJs 中使用 expand、reduce 运算符,因为我与其他为我提供“nextPage”链接的 api 做了类似的事情,但在这种特殊情况下我遇到了无限循环。

我知道问题是nextPosition当expand的输出再次通过expand运行时变量没有被更新,但我不确定是否可以使用这种方法解决这个问题。

是否可以通过递归函数使用扩展和缩减,如果可以,我需要做什么来修复以下问题?

private async retreivePagedRecords<T>(companyURL: string, query: string, startPosition: number, totalCount: number, transformFn: (qbData: any) => T[]): Promise<T[]> {

        const headers = this.getHttpConfig();
        let pageQuery = `${query} STARTPOSITION ${startPosition} MAXRESULTS ${this.pagingSize}`;
        const nextPosition = startPosition + this.pagingSize;

        const records = await lastValueFrom(this.http.get(`${companyURL}/query?query=${pageQuery}`, headers)
            .pipe(
                map(x => x.data as any),
                map(x => {
                    //Trivial transformation to property names etc.
                    return transformFn(x);
                }),
                expand(x => nextPosition > totalCount ? [] : this.retreivePagedRecords<T>(companyURL, query, nextPosition, totalCount, transformFn)),
                reduce((acc: T[], x: T[]) => acc.concat(x ?? []), []),
                catchError(error => {
                    return of([]);
                })
            ));
        return records;
    }

标签: typescriptrxjs

解决方案


对于您的 EXPAND 运算符,如果条件为假,则必须返回 EMPTY 才能继续

 import { EMPTY } from 'rxjs';

 expand(x => nextPosition > totalCount ? EMPTY : this.retreivePagedRecords<T>(companyURL, query, nextPosition, totalCount, transformFn)),

在这里查看我关于 EXPAND 运算符的帖子https://dev.to/faehmohamed14/recursive-http-calls-the-rxjs-way-d61


推荐阅读