Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't get first item in array Angular

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 : enter image description here

Why is it undefined?

like image 864
Janik Spies Avatar asked Sep 14 '25 08:09

Janik Spies


1 Answers

The problem is the forEach which DOES NOT RETURN the promises you try to wait for. For that reason seasons[0] is still undefined. But since you log the array to the console and THE SAME array object is used inside your callback, the console refreshes the output after the data arrives. If you clone the array before logging, you will see that its empty console.log([...seasons]);

Simply switch forEach to map and use Promise.all.

  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 Promise.all(allSeasons.map(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;
  }
like image 168
kai Avatar answered Sep 16 '25 23:09

kai