【发布时间】:2021-11-25 01:21:17
【问题描述】:
我正在尝试实现以下代码,但出现错误 ERROR Error: Uncaught (in promise): TypeError: Cannot read properties of undefined.下面是我的打字稿代码。我在尝试打印 pokeData 时获取对象列表。我正在尝试将对象列表推送到数组,但出现上述错误。如何将对象列表推送到数组,以便我可以在我的 html 文件中使用 ngFor 操作数组数据。对此的任何帮助表示赞赏。谢谢!
import { Component, OnInit } from "@angular/core";
import { PokemonConvPipe } from "../app/pipes/pokemon-conv.pipe";
@Component({
selector: "app-root",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"],
})
export class AppComponent implements OnInit {
pokemonArray: Array<string> = [];
constructor() {}
ngOnInit() {
this.fetchPokemonList();
}
fetchPokemonList() {
fetch("https://pokeapi.co/api/v2/pokemon?limit=20&offset=0")
.then((response) => response.json())
.then(function (allpokemon) {
allpokemon.results.forEach(function (pokemon) {
let url = pokemon.url;
fetch(url)
.then((response) => response.json())
.then(function (pokeData) {
console.log("pokeData", pokeData); //pokeData prints list of objects.
if (pokeData) {
this.pokemonArray.push(pokeData); // throws error
}
});
});
});
}
}
【问题讨论】:
-
要保持
this相同,请使用箭头函数,而不是常规函数。.then((pokeData) => { -
我仍然收到错误,不确定为什么对象没有被推送到数组。
标签: typescript promise