如何在 Angular 应用程序中从 http 客户端获取嵌套的 [object Object] 数据?

How to GET nested [object Object] data from http client in Angular app?

我在组件中写入特定的嵌套数据时遇到问题。我从 api 加载了关键数据(品牌),但值嵌套数据(模型)不起作用,只能写入 [object Object]。我从服务器到控制台获取的数据:

这显示我在显示器上:

在控制台中我有这个错误:错误类型错误:无法读取未定义的 属性 'map'。

我期待这样的例子:

AUDI - AUDI (brands)
A1 (models)
A2
A3
A4...

BMW
M1
M3
M5...

你知道怎么解决吗?谢谢你的帮助。

我的代码:

app.component.ts

vehicleLists: VehicleLists[] = [];

  constructor(
    private vehicleService: VehicleService,
    private router: Router,
    private vehicleListAdapter: ListAdapter,
  ) {

  }

  ngOnInit(): void {
    this.getLists();
  }

  public getLists() {
    this.vehicleService.getVehicleLists().subscribe(({ brands, models }) => {
      console.log(brands);
      this.vehicleLists = brands;
      models.map(model =>
        this.vehicleLists.push(this.vehicleListAdapter.adapt(model)));
    });
  }

app.component.html

<div *ngFor="let item of vehicleLists">
  <p>{{item.id}} - {{item.name}}</p>
    <p>{{item.models}}</p>
</div>

lists.ts - 型号

export class VehicleLists {
  id: string;
  name: string;
  models: VehicleModel[];
}

export class VehicleModel {
  name: string;
  description: string;
}

车辆-list.adapter.ts

export class ListAdapter implements Adapter<VehicleLists> {
  adapt(item: any): VehicleLists {
    const obj = new VehicleLists();
    obj.name = item.name;
    obj.id = item.id;
    obj.models = item.models;
    return obj;
  }
}

vehicle.service.ts

getVehicleLists() {
    return this.http.get<any>(environment.ApiUrl + `/api/url`);
  }

虽然不知道是什么原因,但类似的事情在我身上发生过很多次。这会有点愚蠢,但你可以尝试这样的事情。

let myObj = {
  "id": "audi",
  "name": "audi",
  "models": ["a1", "a2", "a3"]
};
let models = [];
let values = Object.values(myObj);
for(var value of values){
  if(Array.isArray(value)) {
    let newObj = new Object();
    newObj["id"] = values[values.indexOf(value) - 2];
    newObj["name"] = values[values.indexOf(value) - 1];
    newObj["models"] = value;
    models.push(newObj);
  }
}

遍历数组中的每个对象。 models 数组不应再显示为 [object object]

您看到的是正常行为,完全符合预期。您不能在 html 中使用一个对象并期望它的内容被渲染。因为 item.models 是一个数组,而且还不清楚单个模型的确切结构是什么,但是您有 2 个选项:

  1. 在模板中使用 json 管道:
<div *ngFor="let item of vehicleLists">
  <p>{{item.id}} - {{item.name}}</p>
  <p>{{item.models | json}}</p>
</div>
  1. 在模型上使用另一个 ngFor,并为每个模型指定要显示的字段:
<div *ngFor="let item of vehicleLists">
  <p>{{item.id}} - {{item.name}}</p>
  <p *ngFor="let model of item.models>{{model.name}}</p>
</div>