Juliano Eibel
Juliano Eibel

Reputation: 17

How to display image of an API via URL with Angular

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

Upvotes: 0

Views: 4105

Answers (1)

Andres2142
Andres2142

Reputation: 2917

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>

Upvotes: 2

Related Questions