angular - Angular / RxJS:发送 API 请求然后轮询另一个端点
问题描述
我想发送一个 API 请求,然后轮询另一个端点,直到success: true
从第二个端点返回带有正文的响应。我正在使用 Angular 的 HTTPClient 来提出我的请求。我最初的想法是这样做:
createConversion(request): Observable<any> {
return this.http.post('/endpoint', request).pipe(
// This is the problem: I want to start polling before this post() call emits
mergeMap((response) => {
// Start polling
return timer(0, 5000).pipe(
takeUntil(this.converted$),
concatMap(() => {
return this.http.get('/second-endpoint')
})
)
})
);
post()
但是,直到第一个调用与第一个请求的响应一起发出,才会调用 mergeMap 。是否有一个 RxJS 操作员可以让我在第一次post()
调用发出之前开始轮询?
解决方案
尝试:
createConversion(request): Observable<any> {
const post$ = this.http.post('/endpoint', request).pipe(startWith(null));
// force fake emission
const get$ = this.http.get('/second-endpoint');
const polling$ = timer(0,5000).pipe(mergeMap(_=> get$), takeUntil(this.converted$));
return post$.pipe(mergeMap(_=> polling$));
}
推荐阅读
- reactjs - 如何从作为 React 上下文使用者的组件返回字符串值
- c# - 控制 DC 缩放的因素是什么?
- pytest - 如何使用 pytest + xdist 调整线程数?
- xml - 如何使用子元素或引用改进 XML 模式?
- php - Ubuntu PHP CLI 是否可以在使用 directoryiterator 时绕过隐藏(点)目录
- php - PHP Mysqli->query() 为 SELECT INNER JOIN 返回 false,Mysqli->error 返回空
- regex - 正则表达式搜索替换国家列表
- java - JAVA - 无法将 src/test/java 导入 src/main/java
- go - Go Tour flowcontrol #5:理解 return 关键字
- javascript - 使用 react-bootstrap 从数组动态创建下拉菜单选项