I'm having a problem with displaying a image from json that is located on api online. Excuse me for my poor angular skills, I just started it 2 weeks ago. I'm trying to access "image1" property from "data" object in json file.
I've tried using reader to read from url and it worked well, but retrieving from api - specifically json's object "data" and property "image1" seems to be a problem. Maybe problem is that my approach is wrong with just setting src to the "data" object, I need to set it to data["image1"], I've tried setting to [src]="data["image1"]
but with no success.
My JSON
[
{
"id": 1,
"type": "car",
"name": "Porsche 911",
"description": "driving machine",
"area_id": null,
"data": {
"name": "JSON Name",
"description": "JSON Description",
"image1": "https://unsplash.com/photos/u6BPMXgURuI"
}
}
]
My interface Car
export interface Car {
id: string;
type: string;
name: string;
description: string;
area_id: string;
data: string;
}
My component html
<tr *ngFor="let i of cars | async">
<td>{{i.id | json}}</td>
<td>{{i.type | json}}</td>
<td>{{i.name | json}}</td>
<td>{{i.description | json}}</td>
<td>{{i.area_id | json}}</td>
<td><img [src]="i.data | json" alt="image"></td>
</tr>
My component ts file
export class CarComponent implements OnInit {
cars: Observable<Car[]>;
constructor(private http: HttpClient) {}
ngOnInit() {
this.cars = this.http.get<Car[]>('https://car-garage-
beta.herokuapp.com/api/cars/porsche');
}
}
In my interface if I set "data" type to string or object I get the same error
net::ERR_UNKNOWN_URL_SCHEME
bind image like this in your *ngFor
<td><img [src]="i.data.image1" alt="image"></td>
and In your interface set "data" type to any
As Ved_Code_it says, bindind [src] to i.data.image1 works:
<td><img [src]="i.data.image1"></td>
By [src]
we can see:
Here I leave some advices for a new angular programer:
data: string;
but what you really expect is an object so you should change it to "data": { "name": string, "description": string, "image1": string }
. This is typescript type definition, and helps the programer not to commit errors but, in the end, when it transpiles to javascript, this code disappears.app.compoenent.html
<div *ngIf="item.icon" class="img">
<img [src]="item.icon">
</div>
my JSON:
{
id: 'App',
title: 'App',
type: 'item',
icon: '.assets/img/sidebar/app.svg'
},
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.