rxjs - 如何根据第一个响应在 RxJS 中发出多个 Ajax 请求
问题描述
我正在使用 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请求并合并到一个流中而不会过多地更改我的代码。
解决方案
我认为最简单的方法是使用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
推荐阅读
- python - pygal 在 x 轴上绘制日期
- pandas - 'record_path' 处的字典在 json_normalize 中没有变平
- php - 从 index.php 访问另一个文件
- jmeter - Jmeter - 如何在 POST 数据中排列值
- web-applications - 现代网络应用架构
- visual-studio-code - VSCode 可以启动一个会随着光标移动而自动扩展的选择吗?
- javascript - React:如何从 vis.js 边缘的点击事件访问组件功能?
- database - postgresql dotnet 核心连接字符串
- python - Pandas:按两列组合分组
- haskell - Codewars(Haskell 随机测试 QuickCheck)