首页 > 解决方案 > 在 HTML Angular 中显示来自 JSON 的图像

问题描述

对不起菜鸟问题。我创建了一个 http 请求并检索了一些 pokemon 数据并将其放入一个名为 pokemon 的对象中,如下所示:

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']
      }

在 HTML 中,我尝试使用 <img src = "{{ pokemon.image }}"/>

但是,唯一出现的是损坏的图像图标,并且出现此错误:GET http://localhost:4200/%7B%20pokemon.image%20%7D 404 (Not Found)

但是当我 console.log pokemon.image 时,完整的 URL 会输出到控制台: https ://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/1.png

我在这里做错了什么?

标签: htmlangularimageapiurl

解决方案


我做了两个改变和它的工作:

1) pokemon:any;   (instead of  pokemon = {};)

2) this.pokemon (instead of  const pokemon)

推荐阅读