首页 > 解决方案 > 无法获得数组Angular中的第一项

问题描述

我从我的 API 中获得了一个系列的一些季节。之后,我想用来seasons[0]获取数组中的第一项。问题是seasons[0]返回undefined

我的代码如下所示:

 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

  }

我的服务如下所示:

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;
  }

控制台输出如下所示: 在此处输入图像描述

为什么呢undefined

标签: arraysangulartypescriptionic-framework

解决方案


问题是forEach不返回您尝试等待的承诺。seasons[0]还是因为这个原因undefined。但是由于您将数组记录到控制台并且在回调中使用了相同的数组对象,因此控制台会在数据到达后刷新输出。如果您在记录之前克隆阵列,您将看到它是空的 console.log([...seasons]);

只需切换forEachmap并使用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;
  }

推荐阅读