Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
132
rated 0 times [  136] [ 4]  / answers: 1 / hits: 17696  / 7 Years ago, tue, december 19, 2017, 12:00:00

I'm trying to refresh an http call every x seconds in angular2.



  ionViewDidLoad() {

let loader = this.LoadingController.create({
'content':'Please Wait'
});
loader.present().then(()=>{
this.http.request('http://mywebserver.com/apps/random.php').map(res=> res.json()).subscribe(data=>{
console.log(JSON.stringify(data));
loader.dismiss();
this.fact = data;
},err=>{
loader.dismiss();
let alert = this.alertCtrl.create({
title: 'Error!',
subTitle: 'Please check your Internet Connectivity',
buttons: ['OK']
});
alert.present();
})
})

}


I get data when the page newly loads. But now my issue is refreshing the http call to get new data every x seconds


More From » angular

 Answers
21

Use Observable.interval:



import {Observable} from 'rxjs/Rx';
...
constructor(...) {
Observable.interval(30000).subscribe(x => { // will execute every 30 seconds
this.ionViewDidLoad();
});
}


OR inside your ionViewDidLoad function:



Observable.interval(3000)
.timeInterval()
.flatMap(() => this.http.request('http://mywebserver.com/apps/random.php')
.map(res=> res.json())
.subscribe(data=>{
console.log(JSON.stringify(data));
loader.dismiss();
this.fact = data;
});


Edit to answer your comment. From the Rxjs docs:




The timeInterval operator converts a source Observable into an
Observable that emits indications of the amount of time lapsed between
consecutive emissions of the source Observable. The first emission
from this new Observable indicates the amount of time lapsed between
the time when the observer subscribed to the Observable and the time
when the source Observable emitted its first item. There is no
corresponding emission marking the amount of time lapsed between the
last emission of the source Observable and the subsequent call to
onCompleted.



timeInterval by default operates on the timeout Scheduler, but also
has a variant that allows you to specify the Scheduler by passing it
in as a parameter.




Basically in this case it would be the reactive/Rxjs way of JavaScript´s native setInterval() function.


[#55635] Saturday, December 16, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
gerardob

Total Points: 571
Total Questions: 115
Total Answers: 96

Location: Cyprus
Member since Mon, Oct 24, 2022
2 Years ago
;