When attempting to retrieve data from an API and store it in an object (model) for logging in the console, it consistently returns undefined. The same issue occurs when attempting to use the data in HTML with databinding, resulting in undefined values as well. However, the data does populate correctly when logged within the subscribe function.
Here's an example of my TypeScript file:
import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import { BannerStat } from 'src/app/models/banner.model';
import { Home, Banner } from 'src/app/models/home.model';
import { HomeService } from 'src/app/services/home.service';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.scss'],
encapsulation: ViewEncapsulation.None
})
export class HomeComponent implements OnInit {
home: Home;
bannerList : Banner[];
constructor(private homeService: HomeService) {}
ngOnInit(): void {
this.handleData();
// The bannerList logs as undefined
// When used in the HTML, it remains undefined as well
console.log(this.bannerList);
console.log(this.topMessage);
}
handleData(): void {
this.homeService.getHomeObject<Home[]>().subscribe({
next: (response) => {
this.home = response[0];
},
error: (err: any) => {
console.log(err);
},
complete: () => {
this.bannerList = this.home.bannersBanners;
// Both of these log the correct data
console.log(this.home.topMessage);
console.log(this.bannerList)
}
}
);
}
}
The object and "list" fail to initialize on time for the ngOnInit or when the page is loaded. Even moving the "handleData()" function to the constructor did not resolve the issue. Despite researching extensively, I am unable to pinpoint the necessary changes to correct this problem...