[英]Can't get weather data from API using angular components
我想使用 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,但是即使這些變量在APIs的數據返回后有正確的數據,cityName也沒有顯示在GraphsComponent的模板中。 這是為什么? 像這樣的情況應該如何處理? 我應該在哪里實際存儲來自天氣 API 的信息? 在組件中還是在服務中?
如您所見,我使用了 promise,因為我認為它會在從 API 收集數據后獲取我的數據,但事實並非如此。
您可能已經注意到,我對 angular 真的很陌生,所以請盡量以我能理解的方式回答。 我知道的和我從官方 angular 2 教程(“英雄之旅”)中學到的一樣多。
除了你在 jQuery 中的混合之外,你在使用function
時會失去this
上下文。 我建議使用lambda 表達式,它保留所述上下文,因此您可以實際保存數據。
所以而不是使用
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;
}
});
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.