Angular2 / 4 - What is the correct way to add a toJSON function to a typescript class?

I have executed the code of this example , but my toJSON () function is not called.

Attempt 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
    }
  }
}

Attempt 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
    }
  }
}

Attempt 3

Identical code for attempt 2 except toJSON:

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

Create some data ... for example:

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

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

In all cases, it does not change template_items for attributes ... what am I missing here?

UPDATE

Provided by plunk by @estus in the comments worked, so I decided to make it in Angular to compare. Here he works.

, , "template_items" . Angular . - , . . , Angular 4.4.6

Angular. , , - ?

, JSON.stringify().

0
1

, , , JSON() replacer.

toJSON() , , . , , .

, template_items , , ONLY, , , , .

, , , return , :

  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>
}
0

Source: https://habr.com/ru/post/1687909/


All Articles