简体   繁体   English

输入从Angular 2中的Observable返回的数据

[英]Inputting data returned from an Observable in Angular 2

So, I'm trying to build an app that will take temperature and humidity data and output those values in the app. 因此,我正在尝试构建一个将获取温度和湿度数据并在应用程序中输出这些值的应用程序。 As of now I can get the data from my mock data in the data.json and output that data in the HTML template. 到目前为止,我可以从data.json中的模拟数据中获取数据,并在HTML模板中输出该数据。

However, what I would like to do is take values at a given time and output a different value based on those values ie take a Fahrenheit value and calculate Celsius, or calculate the variable pressure deficit(VPD) which outputs a value based on the temperature and humidity. 但是,我想做的是在给定时间获取值并根据这些值输出不同的值,即获取华氏值并计算摄氏度,或者计算可变压力不足(VPD),其根据温度输出值和湿度。

My hangup is how to get those values in order to plug them into a formula. 我的困扰是如何获取这些值以便将其插入公式中。 It outputs using the {{...}} just fine, but I haven't a clue how to add/subtract/divide etc. those values. 它使用{{...}}可以很好地输出,但是我不知道如何加/减/除这些值。

Service: 服务:

  getData(): Observable<TempRh[]> {
   return this._http.get('./assets/data.json')
  .map((response: Response) => response.json())
  .do(data => console.log("All: " + JSON.stringify(data)))
  .catch(this.handleError);}

Component: 零件:

  ngOnInit(): any {
    this._dataService.getData()
    .subscribe(
    tempHum => this.tempHum = tempHum,
  );}

Template: 模板:

  <ul>
    <li *ngFor="let tempHum of tempHum">{{tempHum.temperature}} , 
    {{tempHum.humidity}}</li></ul>

Data: 数据:

[
{"date": "2012-05-01", "temperature": 70, "humidity": 70},
{"date": "2012-05-02", "temperature": 74, "humidity": 72},
{"date": "2012-05-03", "temperature": 79, "humidity": 65},
...]

You can do something like this.Inside your component you can declare a function and a new array: 您可以执行以下操作:在组件内部可以声明一个函数和一个新数组:

modifiedTempHum: Array<any>;

private transformTemp(tempHum) {
  for (let item of tempHum) {
    const temperature = item.temperature;
    const humidity = item.humidity;

    // here you do what you want with your variables

    modifiedTempHum.push({ Temperature: temperature, Humidity: humidity });
    }
}

Then you bind the modified array to your html: 然后,将修改后的数组绑定到html:

<ul>
    <li *ngFor="let tempHum of modifiedTempHum">{{tempHum.Temperature}} , 
    {{tempHum.Humidity}}</li></ul>

And you call your function on ngOnInit(): 然后在ngOnInit()上调用函数:

ngOnInit(): any {
    this._dataService.getData()
    .subscribe(
    tempHum => this.transformTemp(tempHum),
  );}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM