redux17
redux17

Reputation: 685

Error trying to diff '[object Object]'. Only arrays and iterables are allowed (Angular 5)

I have issue when I try to show array data in standard html table. There is method is soa.service that get data in array.

service.

get(Type: number, Code: string): Observable<Items[]>  {
    var requestOptions = this.authService.requestOptionsWithToken();
    return this.http.get(this.serviceUrl + 'api/Get/' + Type + '/' + Code, requestOptions)
        .map(this.dataService.extractData)
        .catch(this.dataService.handleError);
}

public extractData(res: any) {
    return res.json() || [];
}

component.ts

chaptersItems: Items[] = [];

soaType: number;
soaCode: string = 'en-us';

ngOnInit() {
    this.onGet(this.Type, this.Code);
}

onGet(Type: number, Code: string) {
    this.service.get(Type, Code)
        .subscribe(
        response => {
            this.chaptersItems = response;
            console.log(this.chaptersItems);
        });

chapter.component.html

    <table>
            <tr *ngFor="let item of chaptersItems">
                <td>{{item.name}}</td>
                <td>{{item.description}}</td>
            </tr>
        </table>

Upvotes: 1

Views: 733

Answers (1)

Explosion Pills
Explosion Pills

Reputation: 191749

Your API returns something like { enabled: true, soaChapters: [] }. The array you want to iterate over is soaChapters. There are several different ways to handle this, but I would do:

this.soaChaptersItems = response.soaChapters;

The error you're getting about diff [object Object] is that Angular is trying to iterate over an object, but that's not allowed. In this case you're trying to iterate over the wrong thing.

Upvotes: 1

Related Questions