我有一个有方法的类:
export class ItemType {
id1: string;
description: string;
treeItemTypeDescription(): string {
return this.id1 + this.description;
}
}
我从Web服务中获取此类的数据并想要调用此方法:
itemTypeResource.parents(this.originalPosition).then((parents: app.domain.ItemType[]) => {
console.log(typeof(parents[0]));
console.log(parents[0].treeItemTypeDescription());
});
但出现错误:
TypeError: parents[0].treeItemTypeDescription is not a function
我认为错误的原因是 JS 对象未与 TS 对象链接。但我不知道如何解决它。
更新:
console.log(Object.getOwnPropertyNames(parents[0]));
仅提供字段,但不提供方法:
["autoincrementedId", "description", "entityType", "excelId", "excelParentId", "id1", "id2", "id3", "id4", "id5", "parentAutoId"]
更新2:
如果我自己创建对象一切正常:
var s = new app.domain.ItemType();
s.id1 = "1";
s.description = "some";
console.log(s.treeItemTypeDescription());
最佳答案
这是我找到的解决方案:
static fromJSON(json: app.domain.ItemType): app.domain.ItemType {
var result = new ItemType();
for (var key in json) {
if(result.hasOwnProperty(key)) {
result[key] = json[key]
}
}
return result;
}
我创建了静态方法来将 JSON 对象转换为 TS 对象
关于angularjs - 将 JSON 对象转换为 TypeScript 类实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36198136/