【问题标题】:ERROR Error: Uncaught (in promise): TypeError: Cannot read properties of undefined - Typescript错误错误:未捕获(承诺中):TypeError:无法读取未定义的属性-Typescript
【发布时间】: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) =&gt; {
  • 我仍然收到错误,不确定为什么对象没有被推送到数组。

标签: typescript promise


【解决方案1】:

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

   
}

【讨论】:

  • 但是我仍然得到同样的错误,this.pokemonArray 抛出错误
  • 我已经编辑了答案,将调用 forEach 的函数也编辑为箭头函数。很抱歉造成混乱。
  • 我仍然得到同样的错误,this.pokemonArray 再次抛出错误。
  • 抱歉,我错过了 forEach 语句中的另一个函数。这应该工作......
  • 完美,感谢成功。
猜你喜欢
  • 2021-04-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-01
  • 2019-06-19
  • 1970-01-01
  • 2020-10-03
相关资源
最近更新 更多