【问题标题】:How to make multiple Ajax request in RxJS based on first response如何根据第一个响应在 RxJS 中发出多个 Ajax 请求
【发布时间】:2018-08-06 17:27:38
【问题描述】:

我正在使用 redux-observable 史诗使用搜索端点从 GitHub 上的特定组织获取存储库。我的主要问题是我需要按“观察者”排序,所以我需要所有的回购,但 GitHub 只允许一个人每页最多返回 100 个。响应包括“total_count”,我可以用它来确定我需要发出多少请求(页数)。到目前为止,这是我的代码:

export const fetchRepos = actions$ =>
  actions$.pipe(
    ofType(FETCH_REPOS),
    switchMap(action =>
      ajax.getJSON(`https://api.github.com/search/repositories?q=org:${action.payload.orgName}&per_page=100`).pipe(
        flatMap((response) => ([setRepos(response.items), setCurrentOrg(action.payload.orgName), fetchReposSuccess(response.item)])),
        catchError(error => of(fetchReposFailed()))
      )   
    )   
  ); 

我想知道如何使用第一个响应的“total_count”属性根据该数字发出更多 ajax 请求并合并到一个流中,而不会过多地更改我的代码。

【问题讨论】:

    标签: rxjs redux-observable


    【解决方案1】:

    我认为最简单的方法是使用expand() 运算符递归地投射来自Ajax 调用的响应,您可以决定是否需要抓取更多页面。因此,您甚至不需要使用 total_count,因为您可以简单地继续下载页面,直到您获得的项目少于您的 per_page 参数:

    这就是我如何从我的帐户中获取所有存储库的示例:

    const PER_PAGE = 10;
    const API_URL = 'https://api.github.com/search/repositories';
    
    const makeAjax = page => ajax.getJSON(`${API_URL}?q=org:martinsik&per_page=${PER_PAGE}&page=${page}`).pipe(
      map(response => ([page, response])),
    );
    
    makeAjax(1)
      .pipe(
        expand(([page, response]) => response.items.length < PER_PAGE
          ? empty()
          : makeAjax(page + 1)
        ),
        map(([page, response]) => response),
        toArray(),
      )
      .subscribe(console.log);
    

    观看现场演示:https://stackblitz.com/edit/rxjs6-demo-kccdwz?file=index.ts

    【讨论】:

    • 真的很酷,谢谢!当我查看您演示的网络选项卡时,我注意到每个 URL 有 2 个请求。一种是“fetch”,另一种是“xhr”。你能解释一下吗?
    • 其中一个总是一些 service worker 响应,我不知道 stackblitz 对它们做了什么,也许它们只是被缓存了。
    • 有没有办法在调用我的其他操作之前将所有项目放入一个平面数组中? toArray() 不太适合我。
    • 您可以通过scan(...).takeLast(1)收集所有回复
    猜你喜欢
    • 2015-07-08
    • 1970-01-01
    • 2021-04-21
    • 2021-11-04
    • 1970-01-01
    • 2021-04-22
    • 1970-01-01
    • 2019-10-27
    • 2010-10-23
    相关资源
    最近更新 更多