I want to get data back from an API but when I want to put the data in an object (model) and log it in the console it gives back undefined.
The same thing when I use it in my HTML with databinding, there its then also undefined. But when I log it to the console on complete in the subscribe
function it does log in the console
My ts 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();
// this gives back undefined banner
// when I use it as data in my html its also undefined
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;
// these both log the correct data
console.log(this.home.topMessage);
console.log(this.bannerList)
}
}
);
}
}
The object and "list" aren't initialised on time the ngOnInit or the page is loaded. I've also tried to put the "handleData()
" function in the constructor but no luck.
I've checked multiple posts and browsed the net but I don't see where I need to change something...