Angular 计时器功能在后续事件中不触发
我有以下函数,它应该每3秒触发一次HTTP Get调用(getPollResults)。我看到的问题是,只有初始事件才会触发Angular 计时器功能在后续事件中不触发,angular,rxjs,rxjs6,rxjs-pipeable-operators,Angular,Rxjs,Rxjs6,Rxjs Pipeable Operators,我有以下函数,它应该每3秒触发一次HTTP Get调用(getPollResults)。我看到的问题是,只有初始事件才会触发 pollResults() { return timer(0, 3000) .pipe( switchMap(() => this.pollService.setPollResults()), tap(results=> { console.log(`updated results: `${results}`);
pollResults() {
return timer(0, 3000)
.pipe(
switchMap(() => this.pollService.setPollResults()),
tap(results=> {
console.log(`updated results: `${results}`);
})
);
}
this.pollResults().subscribe()
如果我删除了switchMap,它工作得很好(我每3秒钟就会看到一个新的控制台日志)。所以我相信这与switchMap的工作原理有关。为什么这会阻碍计时器的新事件?能否向我们展示您的
setPollResults
功能代码?由于switchMap按预期工作,请参见下面的示例:
const{of,timer}=rxjs;
const{switchMap,tap,take}=rxjs.operators;
函数pollResults(){
返回计时器(0,3000)
.烟斗(
轻触(timerval=>console.log(`timer hit:${timerval}`)),
开关映射(()=>of('foo')),
点击(结果=>{
log(`updated results:${results}`);
}),
采取(5)
);
}
pollResults().subscribe()
switchMap
将取消当前请求,如果需要超过3000毫秒
你可以用
mergeMap
发送所有请求或
exhaustMap
等待当前请求完成,然后发送一个新的switchMap
将取消订阅从this.pollService.setPollResults()
返回的当前内部可观测值,并在计时器(0,3000)
发出时订阅一个新的。因此,看起来setPollResults()
不会在3s的时间间隔内发出。服务调用在第一个事件上返回一个值,即使我将计时器扩展到更长的时间间隔,它也不会触发下一个事件。