angularjs - 将 JSON 对象转换为 TypeScript 类实例

标签 angularjs typescript

我有一个有方法的类:

 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/

相关文章:

工厂函数的 TypeScript 定义

带有 Firestore 的 Angular Material MatTableDataSource

javascript - 清除数组后不会更新 ng-options 绑定(bind)变量

angularjs - 范围变量在事件监听器更改后未在 DOM 中更新

javascript - 使用 TypeScript 接口(interface)在 JS 代码中进行运行时验证

javascript - 覆盖 Jasmine 单元测试中的只读对象

reactjs - 如何在 TypeScript 中设置在 JSON 文件上获取 Object.keys 的类型?

angularjs - 没有为 Angular 添加 bower 传递依赖

javascript - 列出 AngularJS 中使用 $http.get 创建的列表中的所有元素

javascript - event.preventdefault 在 Firefox 中不起作用