gpt4 book ai didi

arrays - 无法获取数组 Angular 中的第一项

转载 作者:行者123 更新时间:2023-12-04 09:31:20 24 4
gpt4 key购买 nike

我从我的 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;
}

控制台输出如下所示: enter image description here

为什么未定义

最佳答案

问题是 forEach 不会返回您尝试等待的 promise 。因此 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;
}

关于arrays - 无法获取数组 Angular 中的第一项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62828392/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com