【发布时间】:2017-02-08 16:53:14
【问题描述】:
我正在尝试制作一个列出 5 个城市及其当前天气的天气应用程序。当您点击一个城市时,它会转到一个详细视图,其中显示该城市的 5 天预报。
现在我有一个 weatherItem 类:
export class WeatherItem {
city: string;
description: string;
temperature: number;
}
*这是我的 weatherService 中获取 5 个城市当前天气信息的方法:
fetchCurrent(){
return Observable.forkJoin(
this.http.get('http://api.openweathermap.org/data/2.5/weather?q=Chicago&units=imperial&appid=f630449a4407b742703bf37d8e8c9057').map(
(response) => response.json()),
this.http.get('http://api.openweathermap.org/data/2.5/weather?q=Dallas&units=imperial&appid=f630449a4407b742703bf37d8e8c9057').map(
(response) => response.json()),
this.http.get('http://api.openweathermap.org/data/2.5/weather?q=Milwaukee&units=imperial&appid=f630449a4407b742703bf37d8e8c9057').map(
(response) => response.json()),
this.http.get('http://api.openweathermap.org/data/2.5/weather?q=Seattle&units=imperial&appid=f630449a4407b742703bf37d8e8c9057').map(
(response) => response.json()),
this.http.get('http://api.openweathermap.org/data/2.5/weather?q=Washington&units=imperial&appid=f630449a4407b742703bf37d8e8c9057').map(
(response) => response.json())
);
}
这是我在 WeatherComponent 中调用的方法,它使用我的 weatherService 中的 fetchCurrent() 方法
getWeather(): void {
this.weatherService.fetchCurrent()
.subscribe(data => this.weatherItems = data);
}
它成功地从 openweathermap.org 获取当前天气数据,但在我的 WeatherComponent 我目前正在显示这样的数据:
<ul class="weatherItems">
<li *ngFor="let weatherItem of weatherItems" class="box" (click)="gotoDetail(weatherItem)">
<div class="col-1">
<h3>{{weatherItem.name}}</h3>
<p class="info">{{weatherItem.weather[0].description}}</p>
</div>
<div class="col-2">
<span class="temperature">{{weatherItem.main.temp}}° F</span>
</div>
</li>
</ul>
如何获取 JSON 数据并将其正确映射到我的视图?例如我有
{{weatherItem.city}}
之前我使用的是模拟数据,但现在我必须使用 JSON 数据,除非我使用,否则我无法让视图正确显示城市名称
{{weatherItem.name}}
在 Angular 2 中有没有办法将 JSON 中的“名称”数据绑定到我的 weatherItem.city 属性?
【问题讨论】:
-
数据是什么样的?
-
您是否在控制台中看到任何错误?您如何接收数据并将其转换为 JSON?
-
我在控制台中看不到任何错误,但我想在视图模板中将我的数据显示为 {{weatherItem.city}} 而不是 {{weatherItem.name}} JSON 数据属性。我刚刚添加了调用 http.get 的代码 sn-p。这就是我目前接收我的 5 个城市的数据的方式。
-
数据当前显示每个城市的正确城市名称、温度和天气描述,但前提是我将其绑定到上面 html 中显示的视图
标签: json angular typescript rxjs