【发布时间】: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