如何通过 URL 和 Angular 显示 API 的图像

How to display image of an API via URL with Angular

我正在学习 Angular,为此我一直在根据 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 中的文档本身开发《英雄之旅》教程。我已经设法用这些英雄的 ID 和名称构建了一个列表,但是我找不到任何与显示来自 API 的图像相关的内容。有没有人有任何实用的解决方案或指出我究竟需要学习什么才能完成这项任务?

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>

当前结果

根据您发布的屏幕截图,图片不是 string,而是 object,请在您的界面中进行更改:

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>