首页 > 解决方案 > NgFor 仅支持绑定到 Iterables,例如 Arrays。角度错误,无法将 GET API 用于前端 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 上显示它时 控制台抛出错误“找不到类型为‘object’的不同支持对象‘[object Object]’。NgFor 仅支持绑定到 Iterables,例如数组。”

标签: angularhttpclientangular-httpclient

解决方案


您可以执行以下操作,

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


推荐阅读