【问题标题】:Error trying to diff '[object Object]'. Only arrays and iterables are allowed (Angular 5)尝试区分“[object Object]”时出错。只允许使用数组和可迭代对象(Angular 5)
【发布时间】:2018-07-15 12:51:34
【问题描述】:

当我尝试在标准 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>

【问题讨论】:

    标签: angular typescript


    【解决方案1】:

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

    this.soaChaptersItems = response.soaChapters;
    

    你得到的关于 diff [object Object] 的错误是 Angular 试图迭代一个对象,但这是不允许的。在这种情况下,你试图迭代错误的东西。

    【讨论】:

    • 那是因为你有getSoa 返回Observable&lt;Soa[]&gt;。它应该是Observable&lt;{ enabled: boolean, soaChapters: Soa[] }&gt;,即它与您的类型定义有关,而不是与响应有关。
    • 你的意思是你没有在以前的方法上使用调用?你想避免什么?
    猜你喜欢
    • 2020-08-15
    • 2021-12-21
    • 2018-11-25
    • 2020-05-27
    • 2021-01-09
    • 2021-04-20
    • 2018-09-14
    • 2019-10-26
    相关资源
    最近更新 更多