尝试从服务器获取数据,间隔为服务每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)
})
}