如何使用从 api 收到的数组中的元素填充 mat-option

How to populate mat-option with elements from an array received from api

我有一个问题,我想我遗漏了一些东西,因为我无法使用从 API.

接收到的元素填充 md-option

这是我进行调用的 service.ts,我尝试从 API 检索数据。

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

基本上 api returns 是这样的:

{
"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 中获取元素并填充此垫选项。

你可以这样做

  • 创建 class 汽车
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;
 }
}
  • 然后在您的服务中导入 class 并使用它。
getCars(){
 this.http.get(this.rootURL+'/car/getallcars')
 .toPromise()
 .then(res => {
     this.carList = res.data.map(car => new Car(car))
  });
}

你能试试下面的代码吗?

在您的 service.ts 文件中替换以下代码

getCars(){
  return this.http.get(this.rootURL+'/car/getallcars');
}

在您的 component.ts 文件中

ngOnInit() {
    if (!this.service.formData) {
        this.resetForm();
    }
    this.getCarsData();
}

cars: any = [];
getCarsData(): void{
    this.service.getCars().subscribe(data => {
       console.log(data);
       this.cars = data;
    });
}

在您的 component.html 文件中

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

我看了你上面的回答,我觉得这是一个更好的方法,这里是我的意见:

在您的模型中创建一个新界面: car.ts

export interface Car{
 id: string,
 brand: string, 
 model: string,
 mileage: number,
 isAvailable: boolean
}

service.ts:

getCars(): Observable<Car[]> {
  return this.http.get(this.rootURL+'/car/getallcars');
}

component.ts:

import { Car} from 'src/app/shared/model/car';
import { CarService } from 'src/app/shared/service/car.service.ts';

export class CarComponent implements OnInit {
 

    cars: Car[];
    selected: string;

    constructor(private carservice: CarService) { }  

    ngOnInit(): void {
       this.carService.getCars().subscribe(data => {
         this.cars = data;
      })
     }

}

在您的模板中

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