Periodically updating Observable value in Angular2

2019-08-13 11:37发布

问题:

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