首页 > 解决方案 > 如何使用 Angular 7 在 html 中显示 JSON 数据?

问题描述

我得到低于来自 OpenWeatherMap API 的 JSON 响应。我想在 HTML 表格中显示 CityName、CityCode、Temperature 和 Description。

JSON响应:

cnt : 1
list
0
coord
  lon : 79.85
  lat : 6.93
sys
  type : 1
  id : 9098
  message : 0.0032
  country : "LK"
  sunrise : 1554597365
  sunset : 1554641358
weather
  0
main
  temp : 30
  pressure : 1010
  humidity : 70
  temp_min : 30
  temp_max : 30
visibility : 10000
wind
  speed : 2.6
  deg : 200
clouds
  all : 20
dt : 1554655382
id : 1248991
name : "Colombo"

HTML 文件:

<table class="table table-hover">
          <thead>
            <th>City</th>
            <th>City Code</th>
            <th>Temperature</th>
            <th>Description</th>            
          </thead>
          <tbody>
            <tr>
              <td>{{weather.list.name}}</td>
              <td></td>
              <td></td>
              <td></td>              
            </tr>
          </tbody>
        </table>

Weather.Service.ts:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { map } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class WeatherService {

  apiKey = '9402da6bd74c395f71604c624cc2b231';
  url;

  constructor(private http:HttpClient) { 
    this.url='http://api.openweathermap.org/data/2.5/group?id=';  //API GET URL

  }

  getWeather(cityCode){
    return this.http.get(this.url+cityCode+'&units=metric&appid='+this.apiKey);
  }

}

Home.component.ts :

import { Component, OnInit } from '@angular/core';
import { WeatherService } from "../shared/weather.service";

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {

  location={    
    code: '1248991'
  };

  public weather: any;

  constructor(private weatherService:WeatherService) {

   }

  ngOnInit() {
    this.weatherService.getWeather(this.location.code).subscribe((Response)=>{
      console.log(Response);
      this.weather = Response;
    })
  }

}

这是我在控制台中遇到的错误

错误类型错误:无法读取 Object.eval [as updateRenderer] (HomeComponent.html:30) 处未定义的属性“列表”

标签: jsonangulartypescriptapiangular7

解决方案


It takes time to load data from the server, so for a moment, your weather is undefined and undefined.list throws an error. So You have two options: to use elvis operator in your html weather?.list.name it lets you safely access weather or use <table *ngIf="weather" class="table table-hover"> to check if you have weather fetched. Also, make sure that there is .name attribute and that you don't have to iterate with *ngFor


推荐阅读