Search code examples
angulartypescriptxmlhttprequestundefined

ERROR TypeError: Cannot read property 'name' of undefined


I am learning how to use HTTPClientModule in Angular 4.3 I have imported correctly in app.module.ts and I am trying to make an http Request GET. This is my app.component.ts

import { Component, OnInit } from '@angular/core';
import { HttpClient} from '@angular/common/http';
interface Card {
  card: [{
    cardClass: string,
    cost: number;
  }];
}
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  constructor(private http: HttpClient) {}
  ngOnInit(): void {


    this.http.get<Card>('https://api.hearthstonejson.com/v1/21517/enUS/cards.collectible.json').subscribe(data => {
      console.log(data.card); //This is not working returning undefined
      console.log(data); //This is not working (removing <Card>)
    });

  }

}

Why data.card is undefined? How ca I have access to the element of the object here to pass then into an array of Cards? Thanks for any help


Solution

  • The API returns array of objects, but your Card interface is defining object with card property. You need to use interface that will describe the response, like this:

    interface Card {
      cardClass: string;
      cost: number;
    }
    
    interface CardArray {
      [index: number]: Card;
    }
    
    this.http.get<CardArray>('https://api.hearthstonejson.com/v1/21517/enUS/cards.collectible.json').subscribe(data => {
      console.log(data[0]); // first card
      console.log(data); // all cards
    });
    

    Or even simpler approach:

    this.http.get<Card[]>('https://api.hearthstonejson.com/v1/21517/enUS/cards.collectible.json').subscribe(data => {
      console.log(data[0]); // first card
      console.log(data); // all cards
    });