【发布时间】:2017-02-05 02:39:06
【问题描述】:
我想用 Angular 2 创建一个简单的天气应用,只是为了学习这个框架。
我有 GraphsComponent,我将在其中绘制温度图表。
import { Component, OnInit } from '@angular/core';
import { WeatherAPIService } from './weatherAPI.service';
@Component({
selector: 'my-graphs',
template: '<h1>Charts for {{this.weatherAPIService.cityName}}</h1>',
providers: [WeatherAPIService]
})
export class GraphsComponent implements OnInit {
weatherData = {};
cityName: string = "";
constructor(
private weatherAPIService: WeatherAPIService,
) { }
ngOnInit(): void {
this.weatherAPIService.getWeather("London").then(data => this.weatherData = data);
console.log(this.weatherData); //wrong data
}
}
我还有一个 WeatherAPIService,它提供天气数据:
import { Injectable } from '@angular/core';
@Injectable()
export class WeatherAPIService {
weatherData = {};
cityName: string = "";
getWeatherHelper (city: string) {
var locationData = new Object();
$.get("https://maps.googleapis.com/maps/api/geocode/json?address=" + city, function (data) {
locationData['latitude'] = data.results[0].geometry.location.lat; //latitude
locationData['longitude'] = data.results[0].geometry.location.lng; //longitude
$.ajax({
url: "https://api.darksky.net/forecast/[MyAPIKey]/" + locationData['latitude'] + ',' + locationData['longitude'],
dataType: "jsonp",
success: function (data) {
//alert("The temperatute in " + city + " is " + data.currently.temperature);
this.weatherData = data;
this.cityName = city;
console.log(data); //good data
return data;
}
});
}
}
getWeather(city: string): Promise<string[]> {
return Promise.resolve(this.getWeatherHelper(city));
}
}
我想获取天气数据来显示它。
在 getWeatherFunction 中,我使用了 2 个 API: - 谷歌地理编码以获取我想要天气的城市的纬度和经度 - DarkSky 获取天气(需要经纬度)
问题在于,从 API 获取位置和天气是异步的,因此 getWeatherHelper() 在返回数据之前完成。
这就是为什么我在 WeatherAPIService 中添加了 weatherData 和 cityName 的原因,但是即使这些变量在从 API 返回数据后具有正确的数据,但 cityName 不会显示在 GraphsComponent 的模板中。这是为什么?这种情况应该如何处理?我应该在哪里实际存储来自天气 API 的信息?在组件中还是在服务中?
如您所见,我使用了 Promise,因为我认为它会在从 API 收集数据后获取数据,但事实并非如此。
您可能已经注意到,我对 Angular 真的很陌生,所以请尝试以我能理解的方式回答。 我从官方 Angular 2 教程(“英雄之旅”)中学到的知识一样多。
【问题讨论】:
标签: javascript api asynchronous angular typescript