定期更新Angular2中的Observable值 [英] Periodically updating Observable value in Angular2

查看:168
本文介绍了定期更新Angular2中的Observable值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从HTTP链接中每5秒钟打一次,而且似乎是使用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) {
    return this.http.get(this.URL + 'issue/' + issue + '/getPhaseVotes')
        .subscribe(data => this.phase_votes = data.json(),
                   err => console.log(err),
                   () => this.getStatus(issue));
}

我应该如何每5秒更新一次?

How should I be updating this every 5 seconds?

推荐答案

您可以使用间隔运算符可观察

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

这样你需要调用一次 getPhaseVotes 方法并订阅。每5秒钟,HTTP请求将被透明地执行,并且在订阅的回调中提供结果:

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

这篇关于定期更新Angular2中的Observable值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆