angular - rxjs,switchMap,interval,在预期流的地方提供了“未定义”
问题描述
试图从服务器获取数据,每隔 10 秒间隔一次服务。如果返回价格,则停止间隔。下面的代码:
但我收到错误:
错误类型错误:您在预期流的位置提供了“未定义”。您可以提供 Observable、Promise、Array 或 Iterable。
代码:
public Respond() {
this.dataService.WaitingForServiceRespond()
.pipe((
debounceTime(2000),
switchMap((r: any) => {
if (!r.price) {
setInterval(() => {
return this.Respond();
}, 10000)
} else {
this.dataService.user.payment = r;
console.log('price returned', r);
return ''
}
})
))
.subscribe(e => {
console.log(e)
})
}
解决方案
问题出在你的switchMap
. 它期望返回一个流。你使用时什么也不返回setInterval
。您可以Observable
通过返回interval()
而rxjs
不是调用来返回一个setInterval()
。
import { interval } from 'rxjs';
...
public Respond() {
this.dataService.WaitingForServiceRespond()
.pipe((
debounceTime(2000),
switchMap((r: any) => {
if (!r.price) {
return interval(10000).pipe(tap(() => this.Respond()))
} else {
this.dataService.user.payment = r;
console.log('price returned', r);
return of('')
}
})
))
.subscribe(e => {
console.log(e)
})
}
推荐阅读
- reactjs - 汉堡菜单下拉到 xs 调整大小的新行
- codenameone - 检测 Codename One 轻量级日期选择器上的“取消”按下
- sql - SQL Server:使用聚集索引导入大数据
- excel - VBA 公式在第二个空格后删除所有内容
- python - 将 groupby 函数与 .csv 文件中的数据框一起使用并绘制结果
- html - 网页未正确呈现
- javascript - 如何解决 React 应用程序中 Redux 更新过于频繁的问题?
- solr - 根据字段值提升 solr 结果
- android - Android MediaCodec NDK 不使用 SPS/PPS VUI
- node.js - 无法在 Heroku 中安装节点