[英]Angular2 Observable with interval
I have a function that needs to be called about every 500ms. 我有一个需要每500ms调用一次的函数。 The way I am looking at doing it with angular2 is using intervals and observables.
我正在考虑使用angular2的方式是使用interval和observables。 I have tried this function to create the observable:
我试过这个函数来创建observable:
counter() {
return Observable.create(observer => {
setInterval(() => {
return this.media.getCurrentPosition();
}, 500)
})
}
With this code for the subscriber: 使用此代码为订阅者:
test() {
this.playerService.initUrl(xxxx) // This works
this.playerService.counter().subscribe(data => {
res => {
console.log(data);
}
})
}
I am very new to observables and angular2 so I might be taking the wrong approach completely. 我对于observables和angular2非常新,所以我可能完全采取了错误的方法。 Any help is appreciated.
任何帮助表示赞赏。
The Observable
class has a static interval
method taking milliseconds (like the setInterval
method) as a parameter: Observable
类有一个静态interval
方法,以毫秒为单位(如setInterval
方法)作为参数:
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);
}
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.