I'm newbie with Angular.
I'm trying to save data in a class to read them into a component. I noticed that before the class is completely read, the component hurries the results, which have not yet been produced, then printing an error message:
Only later it prints the values correctly. But only and exclusively within the subscribe
, as can be seen from the image.
This is my class:
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 this is my (premature) component:
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 remember that something similar happened to me with javascript, but the context was easier to solve (that it was asynchronous?).
I am very curious to clear this question.