我正在尝试实现angular2-datagrid followig this tutorial
我的模特:
export class Inventory{
active: boolean;
constructor(public id: number,
public article: string,
public description: string,
public quantity: number,
public price : string,
public imgURL: string,
public createdAt: string,
public updatedAt: string) {
this.active = true;
}
}
我的组件专门用于ngOnInit:
this.getAllInventory();
this.table = new NgDataGridModel<Inventory>([]);
for (let inv in this.allInventories) {
this.table.items.push(new Inventory(
inv.id,
inv.article,
inv.description,
inv.quantity,
inv.price,
inv.imgURL,
inv.createdAt,
inv.updatedAt)
);
}
this.getAllInventory()是一个调用web服务并填充for循环中allInventories的方法。
这里的方法:
getAllInventory(){
this.inventoryService.getAllInventory().subscribe(
data=>{
console.log(data);
this.allInventories = data;
},
err=>{
alert ("Error getting inventories");
console.error(err);
}
);
}
这里是调用服务的方法,此方法返回一个json数组的库存:
getAllInventory(){
var headers = new Headers();
headers.append("Content-Type", 'application/json');
headers.append('Authorization', `Bearer ${this.globalVar.getToken()}`);
var options = new RequestOptions({ headers: headers });
var result = this.http
.get(this.globalVar.getHost() + "inventory", options)
.map((response: Response) => response.json());
return result;
}
我的错误:在de for循环中,对象inv在其属性中告诉我:属性'id'在类型字符串中不存在,并且与所有属性相同。我该怎么解决?
答案 0 :(得分:1)
这意味着Angular 2模型中使用的Inventory内每个属性的类型与服务器数据的类型不匹配。
两个选项
使用以下代码并投射属性
getAllInventory(){ this.inventoryService.getAllInventory()。认购( 数据=&GT; { 的console.log(数据); 让tempInventory:库存
data.forEach((item) => {
tempInventory=new Inventory();
tempInventory.id: _.toInteger(item.id),
tempInventory.article: item.article.toString(),
tempInventory.description: item.description.toString(),
tempInventory.quantity: _.toInteger(item.quantity),
tempInventory.price : item.price.toString(),
tempInventory.imgURL: item.imgURL.toString(),
tempInventory.createdAt: item.createdAt.toString(),
tempInventory.updatedAt: item.updatedAt.toString()
this.allInventories.push(tempInventory);
})
console.log(this.allInventories);
},
err=>{
alert ("Error getting inventories");
console.error(err);
});
}