我正在尝试使用开放天气地图api在Angular 2中制作天气应用程序。我在我的应用程序中安装了HttpModule,位于app.module.ts中。我还在app.component.ts中导入了Http,我正在运行该程序。
例如,我想获得休斯顿天气的json数据。我的代码如下:
import { Component, OnInit } from '@angular/core';
import { Http } from '@angular/http'
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
newdata;
constructor (private http: Http) {}
ngOnInit(): void{
this.http.get('http://api.openweathermap.org/data/2.5/weather?q=houston&units=imperial&APPID=hiddenforstackoverflow').subscribe(data => {
this.newdata= data
})
}
getData(){
console.log(this.newdata)
}
然而,在运行getData()函数时,控制台并没有真正显示我的预期。
headers:Headers {_headers: Map(1), _normalizedNames: Map(1)}
ok:true
status:200
statusText:"OK"
type:2
url:"http://api.openweathermap.org/data/2.5/weather?q=houston&units=imperial&APPID=d3758344ecd26680d1ae2845dcfbbaf7"
_body:"{"coord":{"lon":-95.36,"lat":29.76},"weather":[{"id":803,"main":"Clouds","description":"broken clouds","icon":"04n"}],"base":"stations","main":{"temp":74.17,"pressure":1014,"humidity":83,"temp_min":73.4,"temp_max":75.2},"visibility":16093,"wind":{"speed":5.82},"clouds":{"all":75},"dt":1508550780,"sys":{"type":1,"id":2638,"message":0.1571,"country":"US","sunrise":1508588841,"sunset":1508629448},"id":4699066,"name":"Houston","cod":200}"
__proto__:Body
我需要访问 _body 中的参数(例如坐标,温度等),但是使用data._body不起作用。 我是Angular的新手,我习惯在vanilla javascript中调用API,在那里我使用了ajax方法。
答案 0 :(得分:1)
旧Http服务并未尝试猜测内容类型,因此您必须在回复中致电.json()
:
this.http.get('http://api.openweathermap.org/data/2.5/weather?q=houston&units=imperial&APPID=hiddenforstackoverflow').subscribe(data => {
this.newdata= data.json();
})
使用不再需要的新HttpClient服务。