Check the change of api with observable and update data

时间:2017-10-12 10:15:32

标签: angular api web ionic-framework observable

I have a web service that provide information about the (last) song that is currently playing on a radio.

How can my observable update the data from my http request by itself ?

My provider:

  load() : Observable<{}> {
    return this.http.get(this.URL).map(res => res.json());
  }

My component:

this.radio.load().subscribe(data => {
  console.log(data)
})

What I want, basically is "data" to be updated every time the web service response change ! How can i do that ?

Thank you very much

1 个答案:

答案 0 :(得分:0)

您可以执行以下操作:在您的组件中,每隔10秒调用load(),并检查数据是否已更改(我相信您要在组件上保存最多的属性最近的数据)。

以下是使用RxJS的方法:

IntervalObservable.create(10 * 1000 /* 10 seconds */)
    .takeWhile(() => this.alive) // only fires when component is alive
    .subscribe(() => {
        .radio.load()
        .subscribe(data => {
            /* ...check if data has changed... */
            console.log(data);
        });
});

关于this.alive - 这只是组件被销毁时(即调用ngOnDestroy时)需要设置为false的组件上的属性,并且需要设置为true时组件已初始化(可能在ngOnInit)。

(当然,您可以使用更传统的setIntervalclearInterval方式来做同样的事情。)