Reputation: 165
I am trying to make a weather app in Angular 2 using the open weather map api. I have the HttpModule installed in my app, in app.module.ts. I have also imported Http in app.component.ts where I am running the program.
For example, I want to get the json data for the weather in Houston. my code is the following:
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)
}
However upon running the getData() function the console does not really show what I expected.
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
I need to access the parameters inside _body (such as coordinates, temperature, etc) however using data._body does not work. I am new to Angular and am used to calling APIs in vanilla javascript, where I used the ajax method.
Upvotes: 0
Views: 695
Reputation: 14257
The old Http service doesn't try to guess the content type, therefore you have to call .json()
on your response:
this.http.get('http://api.openweathermap.org/data/2.5/weather?q=houston&units=imperial&APPID=hiddenforstackoverflow').subscribe(data => {
this.newdata= data.json();
})
With the new HttpClient service that's not needed anymore.
Upvotes: 1