我想使用角度2创建一个简单的天气应用程序,只是为了学习此框架。无法使用角度组件从API获取天气数据
我有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的信息?在组件中还是在服务中?
正如你所看到的,我使用了诺言,因为我认为它会在收集到API之后得到数据,但它不会。
正如您可能已经注意到的那样,我真的很陌生,所以请尝试以我能理解的方式回答。 我从官方角度2教程(“英雄之旅”)中学到的知识。
不错,现在我明白了显示的城市名称。 – Loreno
太棒了!顺便说一下:如果只有一个地方可以检索数据,将其存储在服务中可以。但是,如果有更多的地方,你可能需要一点重构。 – rinukkusu