代码之家  ›  专栏  ›  技术社区  ›  rmcsharry

Angular2/4-向typescript类添加toJSON函数的正确方法是什么?

  •  1
  • rmcsharry  · 技术社区  · 8 年前

    this example 但是我的toJSON()函数没有被调用。

    尝试1

    export class Template {
      constructor(
      ) {}
    
      public id: string
      public account_id: string
      public name: string
      public title: string
      public info: string
      public template_items: Array<number>
    
      public toJSON = function() {
        return {
          attributes: this.template_items
        }
      }
    }
    

    尝试2

    interface ITemplateSerialized {
      attributes: Array<number>
    }
    
    export class Template {
      constructor(
      ) {}
    
      public id: string
      public account_id: string
      public name: string
      public title: string
      public info: string
      public template_items: Array<number>
    
      toJSON(): ITemplateSerialized {
        return {
          attributes: this.template_items
        }
      }
    }
    

    尝试3

      public toJSON = function(): ITemplateSerialized {
        return {
          attributes: this.template_items
        }
      }
    

    let t = new Template();
    t.name = "Mickey Mouse"
    t.template_items = [1,2,3]
    

    console.log(JSON.stringify(t));

    更新

    在评论中@estus提供的plunk有效,所以我决定在Angular中制作一个,以进行比较。 Here it is 这是可行的。

    当我写这个问题时,为了使代码更容易理解,我把“template\u items”做成了一个数字数组。但在我的实际角度项目中,它是一个自定义对象数组。 Here 是一个显示该结构的plunker。它也起作用。和 another plunker 角度工作4.4.6

    但是这个相同的设置在我的角度项目中不起作用。所以问题是以防万一

    在我的项目中,我从JSON返回了一个完全空的对象。stringify()。

    1 回复  |  直到 8 年前
        1
  •  1
  •   rmcsharry    8 年前

    所以,我似乎混淆了toJSON()的工作原理和stringify replacer函数的工作原理。

    使用toJSON()时,您提供的函数将仅返回您指定的项。我的印象是,它将返回所有属性,只更改您在函数中指定的属性。

    因此,在我的项目中,在第一次创建对象时没有template\u项,因为这是唯一的属性,我的序列化接口指定了所有其他属性,因此删除了一个空对象。

    因此,解决方案是在函数返回语句和序列化接口中指定所有属性:

      toJSON(): ITemplateSerialized {
        return {
          id: this.id,
          account_id: this.account_id,
          name: this.name,
          title: this.title,
          info: this.info,
          attributes: this.template_items
        }
      }
    
    export interface ITemplateSerialized {
      id: string,
      account_id: string,
      name: string,
      title: string,
      info: string,
      attributes: Array<TemplateItem>
    }