我正在尝试在 angular2 中每 x 秒刷新一次 http 调用.
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();
})
})
}
我在页面新加载时获取数据.但现在我的问题是刷新 http 调用以每 x 秒获取新数据
I get data when the page newly loads. But now my issue is refreshing the http call to get new data every x seconds
使用 Observable.interval:
import {Observable} from 'rxjs/Rx';
...
constructor(...) {
Observable.interval(30000).subscribe(x => { // will execute every 30 seconds
this.ionViewDidLoad();
});
}
或者在你的 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;
});
编辑以回答您的评论.来自 Rxjs 文档:
Edit to answer your comment. From the Rxjs docs:
timeInterval 运算符将源 Observable 转换为Observable 发出指示之间经过的时间量的指示源 Observable 的连续发射.第一次发射从这个新的 Observable 中可以看出两者之间经过的时间量观察者订阅 Observable 的时间和时间当源 Observable 发出它的第一项时.没有相应的排放标记之间经过的时间量源 Observable 的最后一次发射和随后的调用已完成.
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 默认操作超时Scheduler,但也有一个变体,允许您通过传递它来指定调度程序in 作为参数.
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.
在这种情况下,它基本上是 JavaScript 原生 setInterval()
函数的响应式/Rxjs 方式.
Basically in this case it would be the reactive/Rxjs way of JavaScripts native setInterval()
function.
这篇关于以角度每 x 秒发出一次 http 请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!