NgFor 仅支持绑定到 Iterables,例如 Arrays。 Angular 错误,无法对前端使用 GET API HTML

NgFor only supports binding to Iterables such as Arrays. Angular error, unable to use GET API for front end HTML

我的component.ts文件

export class TeamComponent implements OnInit {

    teams: any;

    constructor(private http: HttpClient) { }

    ngOnInit(): void {
        let resp = this.http.get("https://api.squiggle.com.au/?q=teams");
        resp.subscribe((data) => this.teams = data);
    }
}

我的HTML文件

<section class="teams container text-center">
    <h1>List of Teams</h1>
        <table class="table table-dark">
        <thead>
            <tr>
                <th scope="col">ID</th>
                <th scope="col">Abbrev</th>
                <th scope="col">Logo</th>
                <th scope="col">Team Name</th>
            </tr>
        </thead>
        <tbody>
            <tr *ngFor="let team of teams">
                <td>{{team.id}}</td>
                <td>{{team.abbrev}}</td>
                <td>{{team.logo}}</td>
                <td>{{team.name}}</td>
            </tr>
        </tbody>
    </table>
</section>

我可以通过 HTTP 客户端控制台记录我的团队数据,但是当我尝试通过声明 team: any 来在 HTML 上显示它时;控制台抛出错误 "Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays."

您正在尝试迭代未初始化的 teams: any。您可以更改 teams 的声明,它应该会修复它:

teams: any[] = [];

此外,从 API 返回的根内容是 object,而不是 array :

ngOnInit(): void {
    let resp = this.http.get("https://api.squiggle.com.au/?q=teams");
    resp.subscribe((data) => this.teams = data.teams); // here, you need to set this.teams from data.teams
}

是的声明部分像这样声明

teams;

这个错误让我认为您正在尝试迭代一个对象。

尝试像这样使用 keyvalue 管道:

<tr *ngFor="let team of teams | keyvalue">

您可以执行以下操作,

this.httpClient.get("https://api.squiggle.com.au/?q=teams").subscribe((res: any) => {
         this.responseData = JSON.parse(JSON.stringify(res))["teams"];
        },
        err => {
          console.log(err);
        },
        () => {
          console.log(this.responseData);
         }
       )
      }

您现在应该能够使用 *ngFor 指令迭代 responseData。

此外,您可以将 responseData 声明为 responseData: any

在您的响应中,您将团队对象作为对象数组 ({teams: Array(18)}),因此您必须分配 this.teamsData = data.teams.