問題描述
我正在嘗試在 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 JavaScript′s native setInterval()
function.
這篇關于以角度每 x 秒發出一次 http 請求的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!