[英]Displaying Image from JSON in HTML Angular
sorry for the noob question.抱歉这个菜鸟问题。 I created an http request and retrieved some pokemon data and put it in an object called pokemon, like so:我创建了一个 http 请求并检索了一些 pokemon 数据并将其放入一个名为 pokemon 的 object 中,如下所示:
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']
}
In the HTML, I tried to create an image with <img src = "{{ pokemon.image }}"/>
在 HTML 中,我尝试用<img src = "{{ pokemon.image }}"/>
创建图像
However, the only thing that appears is a broken image icon and this error apears: GET http://localhost:4200/%7B%20pokemon.image%20%7D 404 (Not Found)但是,唯一出现的是损坏的图像图标,并且出现此错误:GET http://localhost:4200/%7B%20pokemon.image%20%7D 404 (Not Found)
But when I console.log pokemon.image, the full URL is output to the console: https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/1.png但是当我 console.log pokemon.image 时,完整的 URL 是 output 到控制台: https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/1.png
What am I doing wrong here?我在这里做错了什么?
You can try it with this instead:你可以试试这个:
<img [src]="pokemon.image"/>
If this still not works, can you tell me what is the reflected value of that property in your HTML file?如果这仍然不起作用,您能告诉我该属性在您的 HTML 文件中的反映值是多少吗?
<p>{{ pokemon.image }}</p>
I made two changes and its working:我做了两个更改及其工作:
1) pokemon:any; (instead of pokemon = {};)
2) this.pokemon (instead of const pokemon)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.