Angular4 - why is the toJSON () user only configured for new objects?

I have this code. Note that serialization simply renames the template_items property to template_items_attributes:

export class Template {
  constructor(
  ) {}

  public id: string
  public account_id: string
  public name: string
  public title: string
  public info: string
  public template_items: Array<TemplateItem>

  toJSON(): ITemplateSerialized {
    return {
      id: this.id,
      account_id: this.account_id,
      name: this.name,
      title: this.title,
      info: this.info,
      template_items_attributes: this.template_items
    }
  }
}


export interface ITemplateSerialized {
  id: string,
  account_id: string,
  name: string,
  title: string,
  info: string,
  template_items_attributes: Array<TemplateItem>
}

Creating an object locally works fine and builds calls to the toJSON () method.

However, as soon as I submit this object to the API:

  private newTemplate(name: string): Template {
    let template = new Template();
    template.name = name;
    template.account_id = this._userService.user.account_id;
    // next 5 lines are for testing that toJSON() is called on new obj
    let item = new TemplateItem();
    item.content = "Test"
    template.template_items.push(item);
    let result = JSON.stringify(template);
    console.log('ready', result); // SHOWS the property changes
    return template;
  }

  postTemplate(name: string): Observable<any> {
    return this._authService.post('templates', JSON.stringify(this.newTemplate(name)))
      .map((response) => {
        return response.json();
      });
  }

It is saved and returned, but from now on, when I am strict and save again, it DOES NOT call toJSON ().

  patchTemplate(template: Template): Observable<any> {
    console.log('patching', JSON.stringify(template)); // DOES NOT CHANGE!
    return this._authService.patch('templates' + `/${template.id}`, JSON.stringify(template))
      .map((response) => {
        return response.json();
      });
  }

Why does toJSON () work only with new objects?

-1
source share
1 answer

In fact, your question has nothing to do with Angular or Typescript, it's just some JavaScript and the logic behind serialization, and why we serialize objects.

API,

"" API, , JSON. JavaScript, .

Object JavaScript toJSON, , , Template, .

,

const obj = JSON.parse(JSON.stringify(new Template()))
obj.toJSON // undefined

, obj Template. , , Template, .

+1

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


All Articles