【发布时间】: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”,我想它可能是内部保留的!