ERROR Error: Uncaught (in promise): TypeError: Cannot read properties of undefined - Typescript

ERROR Error: Uncaught (in promise): TypeError: Cannot read properties of undefined - Typescript

我正在尝试执行以下代码,但出现错误 ERROR Error: Uncaught (in promise): TypeError: 无法读取未定义的属性。下面是我的打字稿代码。我在尝试打印 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);
        }
      })
      
      
      })
     }) 
   }

   
}