尝试区分[object object]'时出错。只允许数组和迭代(Angular 5)

时间:2018-02-05 15:53:01

标签: angular typescript

当我尝试在标准html表中显示数组数据时,我遇到了问题。有一种方法是soa.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>

1 个答案:

答案 0 :(得分:1)

您的API会返回{ enabled: true, soaChapters: [] }之类的内容。要迭代的数组是soaChapters。有几种不同的方法可以解决这个问题,但我会这样做:

this.soaChaptersItems = response.soaChapters;

您对diff [object Object]的错误是Angular正在尝试迭代某个对象,但这是不允许的。在这种情况下,你试图迭代错误的东西。