首页 > 解决方案 > 如何使用从 api 接收的数组中的元素填充 mat-option

问题描述

我有一个问题,我认为我错过了一些东西,因为我无法使用从 API 接收的元素填充 md 选项。

这是我拨打电话的 service.ts,我尝试从 API 检索数据。

getCars(){
 this.http.get(this.rootURL+'/car/getallcars')
 .toPromise()
 .then(res => this.carList = res as Cars[]);
}

基本上 api 返回如下内容:

{
"id": "b49981fc-730e-49fc-b5e4-0159f4b42c9d",
"brand": "Mercedes",
"model": "G-Klasse",
"mileage": 19000,
"isAvailable": true
}

在 html 我有这样的:

<mat-form-field appearance="fill">
<mat-label>Field</mat-label>
<mat-select name="myField"  #brand="ngModel [(ngModel)]="service.formData.brand">
<mat-option *ngFor ="let car of carList" [value]="car.id" >{{car.brand}}</mat-option>
</mat-select>

问题来了。我不知道我应该如何在 component.ts 中编写以从 API 中获取元素并填充这个 mat-option。

标签: angulartypescriptangular-materialmd-select

解决方案


你可以那样做

  • 创建一个类 Car
export class Car {
 id: string,
 brand: string, 
 model: string,
 mileage: number,
 isAvailable: boolean
 constructor(data) {
    this.id = data.id;
    this.brand = data.brand;
    this.model =  data.model;
    this.mileage = data.number;
    this.isAvailable = data.isAvailable;
 }
}
  • 然后在您的服务中导入类并使用它。
getCars(){
 this.http.get(this.rootURL+'/car/getallcars')
 .toPromise()
 .then(res => {
     this.carList = res.data.map(car => new Car(car))
  });
}

推荐阅读