I am currently working on a project using Angular 6 and encountering some challenges.
Here is the issue at hand: I am facing an error in the HTML Console, which occurs after reloading the page. The error message indicates that the variable "atual" is undefined at the time when my HTML is loaded/created.
My question is: Why is the HTML being loaded before the constructor of my component.ts is called?
I am able to retrieve the data eventually, but I am puzzled as to what mistake I might be making. Do I need to subscribe to the event somewhere prior to the constructor?
https://i.sstatic.net/XnVlZ.png
This is found in my home.component.ts:
atual: Atual;
homeService: HomeService;
constructor(_homeService : HomeService) {
this.homeService.getAtual().subscribe((res: any) => {
console.log('Why is it called after html?');
this.atual = res.data;
});
The atual.ts file looks like this:
export class Atual {
public temperature: number;
public wind_direction: string;
public wind_velocity: number;
public humidity: number;
public condition: string;
public pressure: number;
public icon: string;
public sensation: number;
public date: string;
}
This is from my home.service.ts:
getAtual(): Observable<Atual[]> {
return this.http.get('./assets/atual.json')//, options)
.map((response: Response) =>{
return response.json();
} )
}
And finally, here is a snippet from my home.component.html:
<div>
<mat-card>
<img mat-card-lg-image src="../../assets/img/1.png">
<mat-card-title>{{atual.date}}</mat-card-title>
</mat-card>
</div>
Despite the error, the data is displayed after the service subscribes. It seems to go into the constructor in my component.ts eventually, but should it not do so right from the start?