Angular2 HTTP的间隔 [英] Angular2 http at an interval

查看:215
本文介绍了Angular2 HTTP的间隔的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很新的角度和rxjs。
我想创建一个angular2应用程序,会从staticly提供的文本文件中的一些数据(本地服务器上),我想检索和使用Angular2的HTTP提供商和rxjs的地图在一个固定的时间映射到数据模型间隔(5000)。为了反映给服务txt文件的任何更改。

使用rxjs 4.x的,我知道你可以使用 Observable.interval(5000)做的工作,但它似乎不rxjs 5存在。
我的解决办法目前正在刷新使用&LT整个应用程序; META HTTP-当量=刷新内容=5> 从而重新加载整个页面,从而重新加载数据。

所以,我真的想一些方法来做到这一点与观测工作,也许要检查是否有变化发生。或者只是重新加载数据。

任何帮助或其他/更好的方法将是非常美联社preciated。

我到目前为止有:

  @Injectable()
出口类的DataService {    构造函数(私人HTTP:HTTP){}    的getData(URL){
        返回this.http.get(URL)
            .MAP(RES => {
                返回res.text();
            })
            .MAP(RES => {
                返回res.split(\\ n);
            })
            .MAP(RES => {
                VAR dataModels:DataModel的[] = [];
                res.forEach(海峡=> {
                    变种S = str.split(,);
                    如果(S [0] ==){
                        dataModels.push(新的DataModel(S [0],parseInt函数(S [1]),parseInt函数(S [2])));
                    }
                });
                返回dataModels;
            })
    }
}@零件({
选择:我的应用,
模板:`一些HTML显示data`,
供应商:[DataService的]
出口类AppComponent {数据:DataModel的[];构造函数(DataService的:DataService的){}ngOnInit(){
    this.dataService.getData(网址)。认购(
        RES => {
            this.data =资源;        },
        ERR =>的console.log(ERR)
        ()=>的console.log(数据接收)
        );
    }
}

依赖关系:的package.json
    
    依赖:{
    angular2:^ 2.0.0-beta.3
    引导:^ 4.0.0-alpha.2
    ES6-承诺:^ 3.0.2
    ES6-垫片:^ 0.33.13
    jQuery的:^ 2.2.0
    反映了元数据:^ 0.1.2
    rxjs:^ 5.0.0-beta.0
    systemjs:^ 0.19.20,
    zone.js:^ 0.5.11
  },
  devDependencies:{
    打字稿:^ 1.7.5
  }

index.html的进口:

 <脚本SRC =node_modules / ES6-垫片/ ES6-shim.min.js>< / SCRIPT>
<脚本SRC =node_modules / systemjs /距离/系统polyfills.js>< / SCRIPT><脚本SRC =node_modules / angular2 /包/ angular2-polyfills.js>< / SCRIPT>
<脚本SRC =node_modules / systemjs /距离/ system.src.js>< / SCRIPT>
<脚本SRC =node_modules / rxjs /包/ Rx.js>< / SCRIPT>
<脚本SRC =node_modules / angular2 /包/ angular2.dev.js>< / SCRIPT>
<脚本SRC =node_modules / angular2 /包/ router.dev.js>< / SCRIPT>
<脚本SRC =node_modules / angular2 /包/ http.dev.js>< / SCRIPT>


解决方案

您可以使用观测间隔方法>内Angular2。

 进口{分量,输入}从'angular2 /核心;
从rxjs /接收进口{}观测;@零件({
  选择:我的应用,
  模板:`
    < D​​IV>
      {{信息}}
    < / DIV>
  `
})
出口类AppComponent {
  构造函数(){
    Observable.interval(500)
          。取(10).MAP((X)=> X + 1)
          .subscribe((X)=> {
            this.message = X;
          }):
  }
}

下面是相应的plunkr描述的: https://plnkr.co/edit / pVMEbbGSzMwSBS4XEXJI?p = preVIEW

在此基础上

,你可以将你的HTTP请求:

  initializePolling(){
  返回观测
     .interval(60000)
     .flatMap(()=> {
       返回this.dataService.getData(URL));
     });
}

I am quite new to angular and rxjs. I am trying to create an angular2 app that gets some data from staticly served text file(Locally on server), which I would like to retrieve and map to Datamodel using Angular2's http provider and rxjs's map at a fixed time interval(5000). To reflect any changes to the served txt file.

With rxjs 4.x I know you could use Observable.interval(5000) to do the job, but it does not seem to exist in rxjs 5. My workaround currently refresh the whole application using <meta http-equiv="refresh" content="5" > Which reloads the whole page, and thus reloads the data.

So what I would really like is some way to do this working with observables, maybe to check if any changes have happened. or just to reload the data anew.

Any help or other/better way will be very much appreciated.

What I have so far:

@Injectable()
export class DataService {

    constructor(private http:Http){}

    getData(url) {
        return this.http.get(url)
            .map(res => {
                return res.text();
            })
            .map(res => {
                return res.split("\n");
            })
            .map(res => {
                var dataModels: DataModel[] = [];
                res.forEach(str => {
                    var s = str.split(",");
                    if(s[0] !== "") {
                        dataModels.push(new DataModel(s[0], parseInt(s[1]), parseInt(s[2])));
                    }
                });
                return dataModels;
            })
    }
}

@Component({
selector: 'my-app',
template: `Some html to display the data`,
providers: [DataService],
export class AppComponent {

data:DataModel[];

constructor(dataService:DataService) {}

ngOnInit() {
    this.dataService.getData('url').subscribe(
        res => {
            this.data= res;

        },
        err => console.log(err),
        () => console.log("Data received")
        );
    }
}

Dependencies: package.json "dependencies": { "angular2": "^2.0.0-beta.3", "bootstrap": "^4.0.0-alpha.2", "es6-promise": "^3.0.2", "es6-shim": "^0.33.13", "jquery": "^2.2.0", "reflect-metadata": "^0.1.2", "rxjs": "^5.0.0-beta.0", "systemjs": "^0.19.20", "zone.js": "^0.5.11" }, "devDependencies": { "typescript": "^1.7.5" }

index.html imports:

<script src="node_modules/es6-shim/es6-shim.min.js"></script>
<script src="node_modules/systemjs/dist/system-polyfills.js"></script>

<script src="node_modules/angular2/bundles/angular2-polyfills.js"></script>
<script src="node_modules/systemjs/dist/system.src.js"></script>
<script src="node_modules/rxjs/bundles/Rx.js"></script>
<script src="node_modules/angular2/bundles/angular2.dev.js"></script>
<script src="node_modules/angular2/bundles/router.dev.js"></script>
<script src="node_modules/angular2/bundles/http.dev.js"></script>

解决方案

You can use the interval method of Observable within Angular2.

import {Component,Input} from 'angular2/core';
import {Observable} from 'rxjs/Rx';

@Component({
  selector: 'my-app',
  template: `
    <div>
      {{message}}
    </div>
  `
})
export class AppComponent {
  constructor() {
    Observable.interval(500)
          .take(10).map((x) => x+1)
          .subscribe((x) => {
            this.message = x;
          }):
  }
}

Here is the corresponding plunkr describing this: https://plnkr.co/edit/pVMEbbGSzMwSBS4XEXJI?p=preview.

Based on this, you can plug your HTTP request:

initializePolling() {
  return Observable
     .interval(60000)
     .flatMap(() => {
       return this.dataService.getData('url'));
     });
}

这篇关于Angular2 HTTP的间隔的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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