typescript - 错误错误:未捕获(承诺中):TypeError:无法读取未定义的属性-Typescript
问题描述
我正在尝试实现以下代码,但出现错误 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
}
});
});
});
}
}
解决方案
正如Nicholas Tower指出的那样,您必须使用箭头功能以this.pokemonArray
您想要的方式访问。这是因为 Javascript 也有this
一个常规函数。
@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((allpokemon) => {
allpokemon.results.forEach((pokemon) => {
let url = pokemon.url
fetch(url)
.then(response => response.json())
.then((pokeData) => {
console.log('pokeData',pokeData);
if(pokeData){
this.pokemonArray.push(pokeData);
}
})
})
})
}
}
推荐阅读
- bash - df -h if freespace 等于 then | 重击
- javascript - 如何将登录页面的页面重定向到服务器端c#中的索引页面?
- google-sheets - 需要将小区绑定到它的邻居
- mysql - 使用 Mysql 数据库在 Node.js 中手动创建用户时出错“TypeError:User.findById 不是函数
- localization - EWS TimeZone 未找到错误 - 本地化问题?
- firebase - 为什么我的 Firestore 规则阻止我获取我的文档?
- javascript - 如何为 Internet Explorer 11 配置编译器选项
- javascript - 如何向 joi.any() 添加验证函数?
- r - 更改 R Dataframe 中的两个值
- excel - 无法前进到另一张纸