angular - 如何使用从 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。
解决方案
你可以那样做
- 创建一个类 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))
});
}
推荐阅读
- spring-boot - ddl-auto 和 hbm2ddl.auto 有什么区别?
- javascript - 如何查找忽略点或逗号的子字符串的索引
- c# - Nsubstitute 在模拟接口上执行 Action 作为参数
- ubuntu - coc.nvim - 在您的项目根目录中找不到罗马
- firebase - Firebase Google 以身份验证中的用户身份登录
- java - 我在 Windows 上安装了 JDK 和 JRE 时如何运行 Java 代码?
- html - CSS媒体查询不着色文本
- python - 变换频谱以消除正弦扫描失真
- python - 如何使用 Tensorboard 通过 Keras 功能 API 创建活动直方图
- python - 在 AWS Lambda 中使用 boto3 ThreadPoolExecutor 并行检索 S3 对象