首页 > 解决方案 > Angular - 从 json 对象获取属性并将其显示为图像

问题描述

我在显示来自在线 api 的 json 的图像时遇到问题。对不起,我的角度技能很差,我两周前才开始。我正在尝试从 json 文件中的“数据”对象访问“image1”属性。

我尝试使用阅读器从 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

标签: angular

解决方案


在你的 *ngFor 中绑定这样的图像

<td><img [src]="i.data.image1" alt="image"></td>

并在您的界面中将“数据”类型设置为任何


推荐阅读