Recently, I encountered an issue where I couldn't retrieve the length of a dynamically generated array in my Angular application's ngOnInit() method.
@Component({
selector: 'rise-our-champions',
templateUrl: './our-champions.component.html',
styleUrls: ['./our-champions.component.css']
})
export class OurChampionsComponent implements OnInit {
champs: any = [];
ngOnInit() {
this.getChampions(0, 12, 'created_at', 'desc', this.campaignId);
console.log(this.champs);
console.log(this.champs.length); //<================= This displays 0 where as my array populates with 4 values.
}
getChampions(offset: any, size: any, sort: any, order: any, id: any) {
this._restApiService.getCampaignChampion(offset, size, sort, order, id).subscribe(
data => {
// this.champions = data['champions']
data['champions'].forEach((champion: any) => {
this.champs.push(champion);
});
if (data['champions'].length < 12) {
this.showMore = false;
} else {
this.showMore = true;
}
},
error => {
if (error.status == 400) {
this.router.navigate(['/error']);
} else {
this.errorMessage = <any>error,
this.missionService.announceMissionToShowCustomAlert({
requestType: FeatureType.showCustomAlert,
title: 'Error',
message: '<p>' + this.errorMessage + '</p>',
redirectType: FeatureType.isError
})
}
},
() => {
}
);
}
Upon calling the function within the ngOnInit() lifecycle hook, the output displayed did not show the correct array length. Here is a snapshot for reference: https://i.sstatic.net/tXXOD.png