Angular2 Observable with interval

狂风中的少年 提交于 2019-12-05 02:10:34

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/37994059/angular2-observable-with-interval

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!