I created a Weather class with methods used to fetch geographical weather info from openweather API.
In my Angular component, I am trying to call the .getWeather(cityName) which gets coordinates for a city then runs another fetch to the weather API to get the weather data for that city. Then that all gets passed to my displayCurrentWeather method which packages that data nice and pretty.
However when calling the getWeather() method from my component class, and assigning it to a variable, I get undefined.
I figure its an issue with promises but I’ve tried several different variations of async/await and I’m not able to get anything.
Here is the class I created
export class Weather {
static displayCurrentWeather(data: {
temp: number;
feels_like: number;
temp_min: number;
temp_max: number;
pressure: number;
humidity: number;
}) {
return data;
}
static fetchWeatherByCoordinates(coords: {
latitude: number;
longitude: number;
}) {
fetch(
`https://api.openweathermap.org/data/2.5/weather?lat=${coords.latitude}&lon=${coords.longitude}&units=imperial&appid=${apikey}`
)
.then(function (response) {
return response.json();
})
.then(function (data) {
console.log(data.main);
console.log(data.weather);
Weather.displayCurrentWeather(data.main);
});
}
getWeather(cityName: string) {
let coords;
fetch(
`https://api.openweathermap.org/geo/1.0/direct?q=${cityName}&limit=1&appid=${key}`
)
.then((response) => {
return response.json();
})
.then((data) => {
coords = {
latitude: data[0].lat,
longitude: data[0].lon,
};
Weather.fetchWeatherByCoordinates(coords);
});
}
}
And here is the component class where I am calling this method:
export class SearchBar {
inputValue: string = '';
fetchWeather() {
const weather = new Weather();
let data = weather.getWeather(this.inputValue); // <---- Data comes back undefined
console.log('Data ' + data);
}
}```
drewhouses is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.