Skip to content Skip to sidebar Skip to footer

Periodically Updating Observable Value In Angular2

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) { retur

Solution 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:


Post a Comment for "Periodically Updating Observable Value In Angular2"