简体   繁体   English

无法在Angular 2中访问JSON对象?

[英]Can't access JSON object in Angular 2?

I am trying to make a weather app in Angular 2 using the open weather map api. 我正在尝试使用开放式天气地图api在Angular 2中创建天气应用。 I have the HttpModule installed in my app, in app.module.ts. 我在我的应用程序app.module.ts中安装了HttpModule。 I have also imported Http in app.component.ts where I am running the program. 我还在运行程序的app.component.ts中导入了Http。

For example, I want to get the json data for the weather in Houston. 例如,我想获取休斯顿天气的json数据。 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. 但是,在运行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

I need to access the parameters inside _body (such as coordinates, temperature, etc) however using data._body does not work. 我需要访问_body内部的参数(例如坐标,温度等),但是使用data._body无效。 I am new to Angular and am used to calling APIs in vanilla javascript, where I used the ajax method. 我是Angular的新手,并且习惯于使用ajax方法在香草javascript中调用API。

The old Http service doesn't try to guess the content type, therefore you have to call .json() on your response: 旧的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();
})

With the new HttpClient service that's not needed anymore. 使用新的HttpClient服务,不再需要。

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

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