具有间隔的Angular2 Observable [英] Angular2 Observable with interval
本文介绍了具有间隔的Angular2 Observable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个需要每500ms调用一次的函数。我正在考虑使用angular2的方式是使用interval和observables。我已经尝试过这个函数来创建observable:
I have a function that needs to be called about every 500ms. The way I am looking at doing it with angular2 is using intervals and observables. I have tried this function to create the observable:
counter() {
return Observable.create(observer => {
setInterval(() => {
return this.media.getCurrentPosition();
}, 500)
})
}
使用此订户代码:
test() {
this.playerService.initUrl(xxxx) // This works
this.playerService.counter().subscribe(data => {
res => {
console.log(data);
}
})
}
我对于observables和angular2非常新,所以我可能完全采取了错误的方法。任何帮助表示赞赏。
I am very new to observables and angular2 so I might be taking the wrong approach completely. Any help is appreciated.
推荐答案
Observable
类有静态 interval
以毫秒为单位的方法(如 setInterval
方法)作为参数:
The Observable
class has a static interval
method taking milliseconds (like the setInterval
method) as a parameter:
counter() {
return Observable
.interval(500)
.flatMap(() => {
return this.media.getCurrentPosition();
});
}
在您的组件或任何地方:
And in your component or wherever:
test() {
this.playerService.initUrl(xxxx) // This works
this.playerService.counter().subscribe(
data => {
console.log(data);
}
);
}
这篇关于具有间隔的Angular2 Observable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文