首页 > 解决方案 > 从嵌套数组中检索数据

问题描述

我已经尝试了几乎所有东西,但我一直在努力使用 HTML 来检索我的数组。

我确实得到了一份球队名单,但没有出现每支球队的球员(孩子)。

应该是这样的;

HTML

 <h3>Registered teams</h3>
 <ul>
  <li *ngFor='let team of teams;let i = index'>{{ team.Name }} (id: {{ team.id }})
    <ul>
        <li *ngFor='let players of team.players;let j = index'>{{ player.Name }} ({{ players.id }})</li>
    </ul>
  </li>
</ul>

JSON

    "id": 1,
    "Name": "TEAM A",
    "Active": true,
    "created_at": "2019-09-12T13:56:52.045Z",
    "updated_at": "2019-09-12T14:30:42.533Z",
    "Players": [
      {
        "id": 1,
        "Name": "PLAYER1",
        "Active": null,
        "created_at": "2019-09-12T13:56:41.496Z",
        "updated_at": "2019-09-12T14:30:42.540Z"
      },
      {
        "id": 2,
        "Name": "PLAYER2",
        "Active": true,
        "created_at": "2019-09-12T14:00:12.149Z",
        "updated_at": "2019-09-12T14:30:42.540Z"
      }

模型.ts

export class Team {
id: number;
name: string;
active: boolean;
players: {
    id: number;
    name: string;
}}

标签: arraysangularnested

解决方案


您的 json 正在返回Players,您正在引用players并且您编写了let players of team.players.

它应该是:

<li *ngFor='let players of team.Players;let j = index'>{{ players.Name }} ({{ players.id }})</li>


推荐阅读