I get some seasons of a series from my API.
After that, I want to use seasons[0] to get the first item in the array.
The problem is that seasons[0] returns undefined.
My Code looks like this :
async ionViewWillEnter() {
const seasons = await this.serieService.fetchCompleteSerie(this.serie);
this.seasons = seasons;
console.log(seasons); //output below
console.log(seasons[0]); //undefined
this.selected = seasons[0]; //undefined
}
my service looks like this:
async fetchCompleteSerie(serie: Serie) {
let allSeasons: any;
let serieSeasons = [];
let allEpisodes: any;
let seasonEpisodes: any;
allSeasons = await this.http.get('https://www.myapp.com/api/seasons/', this.httpOptions).toPromise();
await allSeasons.forEach(async season => {
season["episodes"] = [];
if (season.serie === serie.url) {
allEpisodes = await this.http.get('https://www.myapp.com/api/episodes/', this.httpOptions).toPromise();
allEpisodes.forEach(episode => {
if (episode.season === season.url) {
season.episodes.push(episode);
}
});
serieSeasons.push(season);
}
});
return serieSeasons;
}
The console output looks like this :

Why is it undefined?
await this.serieService.fetchCompleteSerie(this.serie).then(seasons => {this.seasons = seasons});forEachand push your season objects into a new array.then trynewArraySeasons[0]. let me know if it works.