0

I'm learning Angular and for that I've been developing the Tour of Heroes tutorial from the documentation itself in https://angular.io/tutorial/toh-pt0, but I'm trying to apply some more features like bringing the Hero's image through this Heroes API. I've already managed to build a list with the id and name of these heroes, but I can't find anything related to displaying images from an API. Does anyone have any practical solutions or indicate what exactly I need to study to accomplish this task?

Service.ts

import { Injectable } from '@angular/core';

import { HttpClient } from '@angular/common/http'
import { Heroi } from './heroi';
import { Observable, tap } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class ListaHeroisService {

private readonly API = 'https://superheroapi.com/api/5033128890082701/search/id/'

constructor(private http: HttpClient) { }

list() {
  return this.http.get<Heroi[]>(this.API)
  .pipe(
    tap(console.log)
  )
}

}

Component.ts


import { Component, OnInit } from '@angular/core';
import { Heroi } from './heroi';
import { ListaHeroisService } from './lista-herois.service';

@Component({
  selector: 'app-dashboard',
  templateUrl: './dashboard.component.html',
  styleUrls: ['./dashboard.component.css']
})
export class DashboardComponent implements OnInit {

  herois!: Heroi[];
  

  constructor(private service: ListaHeroisService) { }

  ngOnInit() {

    
 
    this.service.list().subscribe((herois:any)=>{
      this.herois = herois.results;
    })
  }

}

heroi.ts

export interface Heroi {
    id: string,
    name: string,
    image: string
}

Component.html


<ul *ngFor="let heroi of herois">
  
    <li>{{heroi.image}} - {{heroi.id}} - {{heroi.name}}</li>

</ul>

Current results enter image description here

1 Answer 1

2

Based on the screenshot you posted, image is not a string, is an object, change this in your interface:

export interface Heroi {
 id: string,
 name: string,
 image: { url: string }
}
<ul *ngFor="let heroi of herois">  
    <li>
       <p>{{ heroi.id }}</p>
       <p>{{ heroi.name }}</p>
       <img  
        *ngIf="heroi.image?.url"
        [src]="heroi.image.url" 
        [alt]="heroi.name">
    </li>
</ul>
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks, but just that change still didn't work. Returned an error error TS2339: Property 'url' does not exist on type 'object'.
@JulianoEibel I have updated my answer, try adding ? operator next to image
Still didn't work. Display the same error. :(
@JulianoEibel, change your interface as I did, your image property is an object, not a string,
Uhuuul!! Now it worked!! Thank you so much!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.