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?
You can do something like this: In your component, call load()
every 10 seconds, and check whether the data has changed (I believe that you'd want to save a property on your component which holds the most recent data).
Here's how to do it with 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);
});
});
Regarding this.alive
- this is merely just a property on your component that needs to be set to false when the component is destroyed (i.e. upon calling ngOnDestroy
), and needs to be set to true when the component is initialized (probably on ngOnInit
).
(you could, of course, use the more traditional setInterval
and clearInterval
way of doing the same thing.)