如何根据第一个响应在 RxJS 中发出多个 Ajax 请求

How to make multiple Ajax request in RxJS based on first response

我正在使用 redux-observable 史诗通过搜索端点从 GitHub 上的特定组织获取存储库。我的主要问题是我需要按 "watchers" 排序,所以我需要所有的回购协议,但是 GitHub 只允许一个到 return 每页最多 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 请求并合并到一个流中而无需过多更改我的代码。

我认为最简单的方法是使用 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