Search code examples
angularhttpclientangular-httpclient

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


My component.ts file

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);
    }
}

My HTML File

<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>

I am able to console log my team data through HTTP Client but when i try to display it on HTML by declaring team: any; Console is throwing error "Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays."


Solution

  • You can do the following,

    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);
             }
           )
          }
    

    You should be able to iterate the responseData using *ngFor directive now.

    Also, you can declare responseData as responseData: any