json - 如何使用 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) 处未定义的属性“列表”
解决方案
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
推荐阅读
- excel - 无法在 Excel 中更改 VBA 表单的 ListBox 属性
- go - 使用 Gingko 和 Gomega 进行异步测试
- algorithm - 一个图可以有多个最小生成树
- ios - 如何减少 UILabel ( Swift ) 行之间的间距?
- python - 如何为这个硒的 HTML 代码找到一个元素?
- cloud - 在云中的 Rundeck 上运行计划作业
- prolog - 在 Prolog 中排除偶数
- php - 在 PHP/Mysql 中,如何在更改存储在配置文件中的 salt 值后访问数据库中的加密数据?
- azure-ad-b2c - 使用 SAML2 B2C 自定义策略的查询字符串声明解析器
- android - Kotlin 无法两次访问片段中的项目