http每隔x秒以角度请求一次 [英] http request every x seconds in angular

查看:126
本文介绍了http每隔x秒以角度请求一次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正试图在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 function:

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时的
之间的时间和
whe的时间n源Observable发出了第一个项目。没有
相应的排放标记了源Observable的
最后一次排放与随后的
onCompleted的调用之间的时间间隔。

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会在超时计划程序上运行,但
也有变量,允许您通过将
作为参数传递来指定调度程序。

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.

这篇关于http每隔x秒以角度请求一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆