html - 在 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
我在这里做错了什么?
解决方案
我做了两个改变和它的工作:
1) pokemon:any; (instead of pokemon = {};)
2) this.pokemon (instead of const pokemon)
推荐阅读
- javascript - 如何等待 module.export 函数完成请求,然后再将其返回值分配给不同 JS 文件中的变量
- sql - sql查询查找和汇总早上下的订单会抛出错误
- swift - Vapor 3:使用 wait() 时检测到 Eventloop 错误
- python - 如何将制表符分隔表中的值粘贴到与第一个文件中第 1 列中的单词匹配的第二个文件中
- python - 重新制作蛇,不能制作更多段
- java - com.abc.serive.MysqlService 中的字段 countRepo 需要找不到类型为“com.abc.repository.ClicksQuickReplyRepository”的 bean
- vb.net - VB.NET 访问本地用户文件夹的权限
- python - PyPlot 在绘图上显示额外的未知数据
- c# - 如何强制 Resharper 考虑条件编译符号
- c# - 从方法 c# 返回数据