【问题标题】:Angular2 ngFor: What am I doing wrong?Angular2 ngFor:我做错了什么?
【发布时间】:2017-02-16 19:55:41
【问题描述】:

我很难克服 Angular2 中似乎很常见的“找不到类型为 'object' 的不同支持对象 '[object Object]'”错误,我希望有人遇到过类似的情况。

这是来自我的服务的(匿名的)JSON,非常简单:

[
    {
        "item_id": 1,
        "item_type": 2,
        "item_name": "Item 1",
        "item_description": "First item"
    },
    {
        "item_id": 2,
        "item_type": 4,
        "item_name": "Item 2",
        "item_description": "Second item"
    }
]

这是描述这些对象的类、服务和组件的内容:

// item.ts
export class Item {
    item_id: number;
    item_type: number;
    item_name: string;
    item_description: string;
}

//item.service.ts snippet
getItems(): Promise<Item[]> {
    return this.http.get('http://apiurl', { withCredentials: true })
    .toPromise()
    .then((response) => {
        let body = response.json();
        return body as Item[];
    })
    .catch(this.handleError);
}

//item.component.ts snippet
items: Item[];

getItems(): void { // Function that calls the item service
    this.itemService
    .getItems()
    .then((items) => {
        console.log(items); // I use this to verify that I'm getting an array.
        this.items = items;
    });
}

最后是 ngFor 组件:

<ul>
    <li *ngFor="let item of items">
        <i class="fa fa-database"></i> {{item.item_name}}
    </li>
</ul>

我看不出这有什么问题。检索到的数据确实到达了 item 组件,这意味着我的导入是正确的,并且在我的 console.log 中显示的绝对是一个数组,具有 __proto__:Array[0] 属性和所有内容。如果我在控制台记录 Angular 教程英雄应用程序,它甚至看起来与输出的内容相同。然而它根本不会遍历数组,坚持认为它是一个对象。

我做错了什么? ngFor 刚刚坏了吗?

编辑 这是完整的(匿名的)类,删除了不相关的部分:

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { Headers, Response, Http, RequestOptions } from '@angular/http';
import { Item } from '../../classes/item/item';
import { ItemService } from '../../services/item/item.service';

@Component({
    moduleId: module.id,
    selector: 'my-items',
    templateUrl: 'items.component.html'
})
export class ItemComponent implements OnInit {
    items: Item[] = [];

    constructor(
    private router: Router,
    private itemService: ItemService
    ) { }

    getItems(): void {
        console.log(this.items);
        this.itemService
        .getItems()
        .then((items) => {
            console.log(items);
            this.items = Array.from(items);
        });
    }

    ngOnInit() {
        this.getItems();
    }
}

编辑 2

我明白了!而且我认为这可能是Angular2中的一个错误。上面,我使用一个名为“items”的通用变量名来清理我的代码。但在实际的生产代码中,变量称为“实体”。一直以来,我都把它命名为这样。一时兴起,我将变量的名称更改为“testentities”,并且成功了!

所以为了确保,我测试了多种变体,并且每次都有效。然后我把它改回“实体”,错误又出现了。它似乎是某种保留变量。

我会对此进行严格测试,如果它始终可以重现,我会在错误跟踪器上报告。

【问题讨论】:

  • 语法看起来不错,所以肯定是错字什么的,因为我没有看到发布的内容有任何问题。确保所有变量都拼写正确并且对象属性拼写正确。还有这个github.com/angular/angular/issues/6392和这个stackoverflow.com/questions/36401069/…
  • @Sasquatch3o3 我仔细检查了变量名,它们都很好。如果我注释掉 ngFor 模板,组件加载时不会出现任何错误。
  • 噢,刚刚发现了一些可能有帮助的东西。如果我注释掉组件中的 this.items = items 行(将 Item[] 数组留空),ngFor still 会引发错误。所以它看到items: Item[] 没有任何变化作为一个对象,而不是一个数组。想法?
  • 好酷,让我再看看
  • @Sasquatch3o3 看看它的样子。变量的真实名称是“entities”,我想它可能是内部保留的!

标签: angular ngfor


【解决方案1】:

试试这个

item.service.ts sn-p

getItems(): Promise<Item[]> {
    return this.http.get('http://apiurl', { withCredentials: true })
    .toPromise()
    .then((response) => {
        let body = response.json();
        return body;
    })
    .catch(this.handleError);
}

item.component.ts sn-p

items: Item[] = []; // For whatever reason it thinks this is an Object

getItems(): void { // Function that calls the item service
    //this.items = Array.from(this.items);
    this.itemService.getItems().then(items => this.items = items);
}

[更新]

Alight,你已经耗尽了我的调试资源,所以我将它带到基础,

Angular 2 HTTP Client 是他们向您展示如何发出 GET 请求的地方。那么HERE 是基于 Promise 的设置。

所以,这就是你的样子。

item.service.ts sn-p

getItems(): Promise<Item[]> {
    return this.http.get('http://apiurl', { withCredentials: true })
    .toPromise()
    .then(this.extractData)
    .catch(this.handleError);
}
private extractData(res: Response) {
  let body = res.json();
  return body || { };
}
private handleError (error: any) {
  // In a real world app, we might use a remote logging infrastructure
  // We'd also dig deeper into the error to get a better message
  let errMsg = (error.message) ? error.message :
    error.status ? `${error.status} - ${error.statusText}` : 'Server error';
  console.error(errMsg); // log to console instead
  return Promise.reject(errMsg);
}

item.component.ts

items: Item[] = [];

getItems(): void {
  this.itemService.getItems().then(items => this.items = items);
}


更新 #2

听起来 OP 发现了他的问题,并且与其中一个变量的名称有关,看起来名为 entites 的变量可能会导致 Angular 2 崩溃。

“但在实际的生产代码中,该变量被称为“实体”。一直以来,我一直都是这样命名的。一时兴起,我将变量的名称更改为“testentities, "而且成功了!

所以为了确保,我测试了多种变体,并且每次都有效。然后我把它改回“实体”,错误又出现了。”

entities: any{}; 

【讨论】:

  • 这是个好主意,但恐怕行不通。 items: Item[] = []; 部分看起来应该强制项目成为一个数组,但完全相同的错误仍然存​​在。
  • @DamonKaswell 你有Array.from(items) 部分吗?
  • 是的,它在里面。但我现在最担心的是,即使我根本不填充数组,ngFor 仍然将它视为一个对象。
  • @DamonKaswell 好的,在console.log(items); // I use this to verify that I'm getting an array. 这一行设置一个断点,当你点击那行时,在开发者控制台中输入this.items instanceof Arrayitems instanceof Array,它们都应该是正确的语句。我知道您认为 this.items 是一个对象,但这将验证它是什么。 Javascript 中的数组只是使用数字而不是字符串的对象
  • 好吧,我想我们变暖了。那没有用,因为在检索数据时已经抛出了错误。所以我在items: Item[] = []; 处设置了一个断点。有趣的是,如果我运行 this.items instanceof Array 然后,它返回 false!
猜你喜欢
  • 2017-01-18
  • 2016-12-28
  • 2011-06-01
  • 1970-01-01
  • 2021-04-14
  • 2021-04-19
  • 2017-03-13
  • 2013-06-24
  • 1970-01-01
相关资源
最近更新 更多