Search code examples
htmlangularhttpobjectpokeapi

Displaying object into HTML in Angular


sorry for the noob question. I created an http request and retrieved some pokemon data and put it in an object called pokemon, like so:

export class AppComponent implements OnInit{
  title = 'Pokedex';
  apiURL = 'https://pokeapi.co/api/v2/pokemon/1';
  pokemon = {};
  constructor(private http: HttpClient){}

  ngOnInit(): void{
    this.http.get(this.apiURL).subscribe(data =>{
        const pokemon = {
          name: data['name'],
          id: data['id'],
          abilities: data['abilities'].map( ability => ability['ability']['name']),
          types: data['types'].map( type => type['type']['name']),
          image: data['sprites']['front_default']
      }
      console.log(pokemon);

When I console log the object, it outputs in the console fine. However, when I try to display it in an html {{ pokemon }} it just returns [object, Object]

How can I get around this?

I have tried the methods suggested below. {{pokemon.name}}, {{pokemon[name]}} and {{pokemon?.name} display a blank page.

{{ pokemon | json }}
returns an empty object, in the form of {}.

Am I perhaps doing something else wrong?


Solution

  • You need to use the json pipe

    <pre>{{ pokemon | json }}</pre>
    

    OR

    
    <div> Id: {{ pokemon.id }} </div>
    <div> Name: {{ pokemon.name }} </div>
    
    
    <div> Abilities:
      <ul>
        <li *ngFor="let ability of pokemon.abilities"> {{ ability }}</li>
      </ul>
    </div>
    
    <div> Types:
      <ul>
        <li *ngFor="let type of pokemon.types"> {{ types }}</li>
      </ul>
    </div>