arrays - 无法获得数组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
?
解决方案
问题是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;
}
推荐阅读
- julia - 在 Julia 中加载 CSV 文件时出现问题
- javascript - React 组件和 js 库之间的 Javascript 通信
- php - Eclipse PHP 页面在 IDE 和浏览器中的显示方式不同
- c++ - 如何处理这个静态断言失败的特征错误?
- php - 队列作业中的 Laravel 和 FFMpeg 出错
- excel - 从内存中释放/释放与清除全局/公共变量 - Excel VBA
- python - 无法在 created_date 过滤我的 Django 模型依赖
- c# - 在 asp .net core web api 中使用 DOCTYPE 发布 xml 请求时出现验证错误
- java - 在不改变程序逻辑的情况下优化给定的解决方案。还要计算时间复杂度
- lua - 在 LUA 中生成星形图案