Angular2中的数据通信

时间:2016-04-25 15:35:55

标签: http typescript angular

我想在Angular2中使用HTTP服务,我有一些顾虑。 我正在从openweather API获取meteo数据,我只想将它放在一个typeScript变量(meteo:{})中,并在我的模板中使用它。

以下是我的.ts文件:

meteo.service.ts

import {Injectable} from "angular2/core";
import {Http, Response} from "angular2/http";
import {Observable} from "rxjs/Observable";
import {MeteoComponent} from "../widgets/meteo/meteo.component";
import {Meteo} from "../widgets/meteo/meteo";

@Injectable()
export class MeteoService {

constructor(private http: Http) {}

// Nom de la ville sans accent
private _ville = 'Montreal';
// Initiales du pays
private _country = 'ca';
// Units (metric/imperial)
private _units = 'metric';
// API KEY
private _APPID = 'ewfw54f5646';
// url to get data
private _meteoUrl = 'http://api.openweathermap.org/data/2.5/weather?q='+this._ville+','+this._country+'&units='+this._units+'&APPID='+this._APPID;

getMeteo (): Observable<Meteo> {
    return this.http.get(this._meteoUrl)
        .map(this.extractData)
        .catch(this.handleError);
}

private extractData(res: Response) {
    if(res.status < 200 || res.status >= 300) {
        throw new Error('Bad response status: ' + res.status);
    }
    let body = res.json();
    return body || { };
}

private handleError(error: any) {
    let errMsg = error.message || 'server error';
    console.error(errMsg);
    return Observable.throw(errMsg);
}

}

meteo.component.ts

import {Component, OnInit, OnChanges, AfterContentInit} from "angular2/core";
import {MeteoService} from "../../services/meteo.service";
import {Meteo} from "./meteo";

@Component({
selector: 'meteo',
templateUrl: 'dev/widgets/meteo/meteo.component.html',
providers: [MeteoService]
})

export class MeteoComponent implements OnInit {

errorMessage: string;
meteo: Meteo;

// We inject the service into the constructor
constructor (private _meteoService: MeteoService) {}

// Instantiate data in the ngOnInit function to keep the constructor simple
ngOnInit() {
    this.getMeteo();
}

getMeteo() {
    this._meteoService.getMeteo()
        .subscribe(
            data => this.meteo = data,
            error => this.errorMessage = <any>error);
}

}

meteo.ts

export class Meteo {
    data: {};
}

和meteo.component.html

<span class="meteo">{{meteo | json}}°C</span>

实际上结果是整个json对象:

{  
   "coord": {  
     "lon":-73.59,
     "lat":45.51
   },
   "weather":[  
     {  
       "id":803,
       "main":"Clouds",
       "description":"broken clouds",
       "icon":"04d"
     }
   ],
   "base":"cmc stations",
   "main":{  
     "temp":3.96,
     "pressure":1020,
     "humidity":32,
     "temp_min":2,
     "temp_max":6.67
   },
   "wind":{  
     "speed":2.1
   },
   "clouds":{  
     "all":75
   },
   "dt":1461594860,
   "sys":{  
     "type":1,
     "id":3829,
     "message":0.004,
     "country":"CA",
     "sunrise":1461577807,
     "sunset":1461628497
   },
   "id":6077243,
   "name":"Montreal",
   "cod":200
 }

我想只显示临时区域。

如果你有任何想法的人欢迎它!

非常感谢。

2 个答案:

答案 0 :(得分:0)

您可以利用Elvis运算符,因为您的数据是异步加载的:

<span class="meteo">{{meteo?.main.temp | json}}°C</span>

答案 1 :(得分:0)

尝试在this.meteo.data

上设置数据
getMeteo() {
    this._meteoService.getMeteo()
        .subscribe(
            data => this.meteo.data = data,
            error => this.errorMessage = <any>error);
}

然后用

显示它
<span class="meteo">{{meteo.data.main.temp}}°C</span>