首页 > 解决方案 > 错误错误:未捕获(承诺中):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
              }
            });
        });
      });
  }
}

在此处输入图像描述

标签: typescriptpromise

解决方案


正如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);
        }
      })
      
      
      })
     }) 
   }

   
}

推荐阅读