【问题标题】:Can't get first item in array Angular无法获得数组Angular中的第一项
【发布时间】:2020-10-30 20:20:07
【问题描述】:

我从我的 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?

【问题讨论】:

  • 这很奇怪。
  • 我知道。首先我认为这可能是因为异步,但我不知道为什么
  • 当我从信号器集线器获取数据并尝试将值推送到数组时也会发生这种情况,但在我的情况下,我使用过滤器来获取数据并且正在返回数据
  • 不,但你可以试试这样的await this.serieService.fetchCompleteSerie(this.serie).then(seasons => {this.seasons = seasons});
  • Trt 使用forEach 并将您的季节对象推送到新数组中。然后尝试newArraySeasons[0]。让我知道它是否有效。

标签: arrays angular typescript ionic-framework


【解决方案1】:

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

只需将forEach 切换为map 并使用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;
  }

【讨论】:

    猜你喜欢
    • 2017-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-14
    • 2014-05-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多