Periodically updating Observable value in Angular2

霸气de小男生 提交于 2019-12-11 13:37:29

问题


I'd like to hit and display every 5 seconds from a http link, and it seems to be that using angular2, an observable would be the way to go?

getPhaseVotes(issue: string) {
    return this.http.get(this.URL + 'issue/' + issue + '/getPhaseVotes')
        .subscribe(data => this.phase_votes = data.json(),
                   err => console.log(err),
                   () => this.getStatus(issue));
}

How should I be updating this every 5 seconds?


回答1:


You could use the interval operator of Observable:

@Injeactable()
export class SomeService {
  constructor(private http:Http) {}

  getPhaseVotes(issue: string) {
    return Observable.interval(5000).flatMap(() => {
      return this.http.get(this.URL + 'issue/' + issue + '/getPhaseVotes')
        .map(res => res.json());
    });
  }
}

This way you need to call once the getPhaseVotes method and subscribe on it. Every 5 seconds, an HTTP request will be executed transparently and the result provided within the subscribed callback:

@Component({
  (...)
})
export class SomeComponent {
  constructor(private service:SomeService) {
    this.service.getPhaseVotes('someissue')
      .subscribe(data => this.phase_votes = data,
               err => console.log(err),
               () => this.getStatus(issue));
  }
}

This article could give you more hints in its "Polling" section:

  • https://jaxenter.com/reactive-programming-http-and-angular-2-124560.html


来源:https://stackoverflow.com/questions/36086596/periodically-updating-observable-value-in-angular2

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