代码之家  ›  专栏  ›  技术社区  ›  TheUnreal

使用HTTP的Rxjs-获取第一个页面,然后是其余页面

  •  0
  • TheUnreal  · 技术社区  · 6 年前

    我返回一个HTTP规则列表的其余API。我想得到规则的第一页,然后对其余的页面进行并行的HTTP请求。我需要第一页来知道总共有多少页。

    我的目标是:一旦所有的HTTP请求都结束,就返回一个带有所有页面的数据列表的observable(而不仅仅是像现在这样动态地更新一个变量)。

    当前代码:

    getRules(category) {
        this.http.get(`rules?page=0&size=8000&category=${category}`)
          .subscribe((data: any) => {
            let rulesData = [];
            this.loading = true;
            if (data.last === false) {
                rulesData = rulesData.concat(data.content);
              const pages = [];
              if (data.totalPages > 20) {
                data.totalPages = 20;
              }
              for (let i = 1; i <= data.totalPages - 1; i++) {
                pages.push(i);
              }
              return Observable.forkJoin(
                pages.map(
                  i => this.http.get(`rules?page=${i}&size=8000&category=${category}`)
                )
              ).subscribe((event: any) => {
                this.totalCount = event[0].totalElements;
                event.forEach((entry) => {
                  rulesData = rulesData.concat(entry.content);
                });
                this.rulesData = rulesData;
                this.loading = false;
              });
            } else {
              this.appRulesData = data.content;
              this.loading = false;
            }
          }, (err) => {
            this.loading = false;
            this.error = err;
          });
      }
    

    你知道如何使用Rxjs返回一个包含所有页面数据的observable吗?

    0 回复  |  直到 6 年前
        1
  •  0
  •   Valeriy Katkov    6 年前

    如果您只想得到一个可观察的,最好使用 pipe switchMap ,而不是订阅它。我也用过 tap finalize 跟踪进度。

    import { forkJoin, of, throwError } from 'rxjs';
    import { delay, tap, switchMap, finalize } from 'rxjs/operators';
    
    function loadPagesInfo() {
      return of({
        pageCount: 3
      }).pipe(
        delay(1000)
      );
    }
    
    function loadPage(pageIndex) {
      return of({
        pageIndex: 1
      }).pipe(
        delay(1000)
      );
    }
    
    function loadPages() {
      return loadPagesInfo().pipe(
        tap(()=> {
          console.log("loading start");
        }),
        switchMap(pagesInfo => {
          return forkJoin(
            new Array(pagesInfo.pageCount)
              .fill(0)
              .map((_, pageIndex) => loadPage(pageIndex))
          )
        }),
        finalize(() => {
          console.log("loading end");
        })
      );
    }
    
    loadPages().subscribe(result => {
      console.log(`result: ${result}`);
    });
    

    StackBlitz

    推荐文章