[英]Angular - Getting property from json object and displaying it as image
我在顯示來自 api online 上的 json 的圖像時遇到問題。 對不起,我的角度技巧很差,我兩周前才開始。 我正在嘗試從 json 文件中的“data”對象訪問“image1”屬性。
我試過使用 reader 從 url 中讀取並且效果很好,但是從 api 中檢索 - 特別是 json 的對象“data”和屬性“image1”似乎是一個問題。 也許問題是我的方法只是將 src 設置為“data”對象是錯誤的,我需要將它設置為 data["image1"],我已經嘗試設置為[src]="data["image1"]
但是沒有成功。
我的 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"
}
}
]
我的界面車
export interface Car {
id: string;
type: string;
name: string;
description: string;
area_id: string;
data: string;
}
我的組件 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>
我的組件 ts 文件
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');
}
}
在我的界面中,如果我將“數據”類型設置為字符串或對象,我會得到同樣的錯誤
net::ERR_UNKNOWN_URL_SCHEME
在 *ngFor 中綁定這樣的圖像
<td><img [src]="i.data.image1" alt="image"></td>
並在您的界面中將“數據”類型設置為任何
正如 Ved_Code_it 所說, bindind [src] 到 i.data.image1 有效:
<td><img [src]="i.data.image1"></td>
通過[src]
我們可以看到:
在這里,我給一個新的 Angular 程序員留下一些建議:
data: string;
但是您真正期望的是一個對象,因此您應該將其更改為"data": { "name": string, "description": string, "image1": string }
。 這是 typescript 類型定義,有助於程序員不犯錯誤,但最終,當它轉換為 javascript 時,此代碼消失了。app.component.html
<div *ngIf="item.icon" class="img">
<img [src]="item.icon">
</div>
我的 JSON:
{
id: 'App',
title: 'App',
type: 'item',
icon: '.assets/img/sidebar/app.svg'
},
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.