我想使用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中,我使用了两个API:-谷歌地理编码来获取我想要的城市的纬度和经度- DarkSky来获取天气(它需要纬度和经度)
问题是,从API获取位置和天气是异步的,所以getWeatherHelper()在返回数据之前完成。
这就是为什么我在WeatherAPIService中添加了weatherData和cityName,但即使这些变量在从API返回数据后有了正确的数据,cityName也不会显示在GraphsComponent的模板中。为什么会这样呢?这样的情况该如何处理呢?实际上,我应该将天气API的信息存储在哪里?在组件中还是在服务中?
正如您所看到的,我使用了promise,因为我认为在从API收集数据之后,它会让我获得数据,但它没有。
正如你可能注意到的,我对angular是个新手,所以请试着用我能理解的方式来回答。我所知道的和我从官方angular 2教程(“英雄之旅”)学到的一样多。
发布于 2016-09-27 21:02:08
在使用jQuery时,除了混入function
之外,还会失去this
上下文。我建议使用lambda expression,它保留了所说的上下文,因此您可以实际保存数据。
所以不是使用
function (data) {
在需要内联函数的地方开始使用lambda:
(data) => {
应用于您的代码:
getWeatherHelper (city: string) {
var locationData = new Object();
$.get("https://maps.googleapis.com/maps/api/geocode/json?address=" + city, (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: (data) => {
//alert("The temperatute in " + city + " is " + data.currently.temperature);
this.weatherData = data;
this.cityName = city;
console.log(data); //good data
return data;
}
});
});
}
https://stackoverflow.com/questions/39725086
复制相似问题