angular - Angular RxJs:轮询 HTTP 请求,直到超时或来自服务器的肯定响应
问题描述
我是 RxJs 的新手。我需要轮询一个 http 请求并继续轮询,直到我得到一个肯定的响应或指定的时间已经过去(不想永远轮询)。
我正在使用 Angular 8 和 Typescript。这是我的代码:
this.httpClient.get('http://localhost:8060/api/portal/v1/payment/fetch/' + shopId + '/0/10').pipe(
repeatWhen(obs => obs.pipe(delay(5000))),
filter((data: ResponseModel<any>) => {
console.log('Data:' + data);
return data.status === 'success';
}),
take(1)
).subscribe(result => {
console.log('Result: ' + result);
});
上面的代码适用于来自服务器的正面响应,但如果没有正面响应,它会永远轮询,这不是预期的效果。如何在上述功能中添加超时?
解决方案
根据第一条评论中的建议,我调整了一些东西,最后得到了以下可行的方法
// Create an Observable that emits every 5 seconds
interval(5000).pipe(
// Since the httpClient returns an Observable, wrap it with a switchMap
switchMap(() => this.httpClient.get('http://localhost:8060/api/portal/v1/payment/fetch/' + shopId + '/0/10')),
// Filter only the successful http responses
filter((data: ResponseModel<any>) => {
console.log('Data:' + JSON.stringify(data));
return data.status === 'success';
}),
// Emit only the first value emitted by the source
take(1),
// Time out after 30 seconds
timeout(30000),
).subscribe((result: ResponseModel<any>) => {
console.log('Result: ' + JSON.stringify(result));
}, error => {
console.log('Error: ' + error);
});
推荐阅读
- python - AttributeError:'NoneType' 对象在 Python 中没有属性 'lower'。如何在标记文本内容之前进行预处理?
- python - 如何将条目转换为字符串
- java - 制作密码密钥验证器,其中一个输出应显示:报告密钥失败的所有规则
- python - Plotly:如何更改跟踪顺序,或在 plotly 中切换轴的两侧?
- git - 无法从本地存储库初始化远程 git 存储库
- python - 在 python 中动态或以编程方式创建函数
- python - nohup:忽略输入,但我的 python 程序确实需要输入
- firebase - “DocumentChange”类型上不存在属性“entryDate”
- javascript - 如何将 HTML 元素分配给 JavaScript 全局变量?
- flutter - 颤振编程