我在克服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>
我没有发现任何问题。 检索到的数据确实到达了项目组件,这意味着我的导入是正确的,并且在我的console.log中显示的内容绝对是一个数组,带有
__proto__:Array[0]
属性和其他所有属性。 它甚至看起来与Console log Angular教程Heroes应用程序输出的内容完全相同。 但是它仅仅不能迭代数组,坚持认为它是一个对象。我做错了什么? 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”来对代码进行了净化。但在真正的生产代码中,变量被称为“entities”。而且一直以来,我都是用这个名字命名的。突发奇想,我把变量的名称改成了“testentities”,它就起作用了!
所以,为了确保,我测试了多种变化,每次都可以工作。然后我又把它改回了“entities”,错误又出现了。它似乎是某种保留变量。
我将严格测试这个问题,如果可以稳定地重现,我将在错误跟踪器上报告它。
this.items = items
这一行(将Item[]数组留空),ngFor仍然会抛出错误。所以它将items: Item[]
视为对象而不是数组。有什么想法吗? - Damon Kaswell