我试图在angular2中每隔x秒刷新一次http调用.
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();
})
})
}
我在新加载页面时获取数据.但现在我的问题是刷新http调用以每隔x秒获取新数据
解决方法:
import {Observable} from 'rxjs/Rx';
...
constructor(...) {
Observable.interval(30000).subscribe(x => { // will execute every 30 seconds
this.ionViewDidLoad();
});
}
或者在ionViewDidLoad函数中:
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;
});
编辑以回答您的评论.来自Rxjs文档:
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 07001, but also
has a variant that allows you to specify the Scheduler by passing it
in as a parameter.
基本上在这种情况下,它将是JavaScript的本机setInterval()函数的reactive / Rxjs方式.