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...
CodePudding user response:
This is due to asynchrone process in handleData().
The problem is that ngOnInit call handleData but doesn't wait for the answer and go on by console logging the object and list (js works like this, it's normal). Then the answer is coming from the api... but to late for the console.log in ngOnInit.
You can turn around this with a .toPromise() and await in the ngOnInit() like:
await handleData().toPromise().then(response => {console.log(response);})
.
CodePudding user response:
You need defined home variable like this home: Home = new Home();
then assign data which come from API. Same for also bannerList:: Banner[] = new Banner[]