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

Time:10-05

I am trying to implement the below code, but i get error ERROR Error: Uncaught (in promise): TypeError: Cannot read properties of undefined. Below is my typescript code. I get list of objects while trying to print pokeData. I am trying to push the object list to an array, but i get the above error. How to push the list of objects to an array so that i can manipulate the array data using ngFor in my html file. Any help on this is appreciated. Thanks!

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

enter image description here

CodePudding user response:

As Nicholas Tower pointed out, you have to use an arrow function to access this.pokemonArray in a way you want. This is because Javascript has this inside a regular function as well.

@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);
        }
      })
      
      
      })
     }) 
   }

   
}
  • Related