As a newcomer to Angular, I am facing an issue with saving data in a class and reading it into a component. It seems that the component is rushing to display results before the class has finished processing them, resulting in an error message being printed prematurely:
https://i.sstatic.net/FZCuJ.png
The correct values are only displayed later on, but strictly within the subscribe
block, as shown in the image.
Here's my class implementation:
import { Injectable } from '@angular/core';
import { WeatherForecastApiService } from '../weatherForecastApiService/weather-forecast-api.service';
@Injectable({
providedIn: 'root',
})
export class WeatherClass {
public weather: WeatherFeature;
constructor(
private wfas: WeatherForecastApiService,
) {
this.wfas.getItalyWeatherData('Pisa').subscribe((response) => {
const ks: string[] = ['name', 'main', 'temp'];
this.weather = {
cityName: response[ks[0]],
degrees: response[ks[1]][ks[2]] - 273.15,
};
console.log('clean print', this.weather.cityName);
console.log('clean print', this.weather.degrees);
});
}
public showValues() {
console.log('undefined print in component', this.weather.cityName);
console.log('undefined print in component', this.weather.degrees);
}
}
And here's my (premature) component code:
import { AfterViewInit, Component } from '@angular/core';
import { WeatherClass } from '../weatherObject/weather-class';
@Component({
selector: 'app-weather-forecast',
templateUrl: './weather-forecast.component.html',
styleUrls: ['./weather-forecast.component.scss'],
})
export class WeatherForecastComponent implements AfterViewInit {
constructor(
private weather: WeatherClass,
) {}
ngAfterViewInit() {
this.weather.showValues();
}
}
I have encountered a similar issue with JavaScript in the past, where asynchronous behavior caused complications. I am eager to resolve this question and understand the underlying concepts better.