简体   繁体   中英

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?

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>

调用属性为{{pokemon?.name}}

You can't use object directly. You have to access object properties by either . (Dot) notation or object[property] way.

In your case, if you want to use the property of name then use

{{ pokeman.name }}

or

{{ pokeman[name] }}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM