Monday, May 13, 2024
 Popular · Latest · Hot · Upcoming
151
rated 0 times [  156] [ 5]  / answers: 1 / hits: 20897  / 8 Years ago, thu, june 23, 2016, 12:00:00

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)
})
}


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. Any help is appreciated.


More From » angular

 Answers
39

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);
}
);
}

[#61670] Tuesday, June 21, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
benitoh

Total Points: 150
Total Questions: 113
Total Answers: 104

Location: India
Member since Wed, Aug 26, 2020
4 Years ago
benitoh questions
Sun, Mar 21, 21, 00:00, 3 Years ago
Mon, May 13, 19, 00:00, 5 Years ago
;