이 코드가 있습니다. 직렬화는 단순히 template_items 속성의 이름을 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>
}
로컬에서 객체를 생성하는 것은 잘 작동하며 stringify는 toJSON () 메서드를 호출합니다.
그러나 일단 해당 객체를 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();
});
}
저장되고 반환되지만 그 시점부터 문자열 화하고 다시 저장할 때 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();
});
}
toJSON ()이 새 객체에서만 작동하는 이유는 무엇입니까?
사실, 귀하의 질문은 Angular 또는 Typescript와 관련이 없으며 직렬화가 작동하는 방식 및 객체를 직렬화하는 이유 에 대한 일부 JavaScript 및 논리 일뿐 입니다.
그 객체를 API에 보내고 저장하고 반환합니다.
API에서 "객체"를 반환하면 JSON 직렬화 된 객체로 구문 분석하는 문자열을 반환합니다. 그런 다음 클래스의 인스턴스가 아닌 일반 JavaScript 객체 를 얻습니다 .
Object
JavaScript의 프로토 타입에는 toJSON
메서드 가 없습니다. 메서드가 있어도 Template
클래스 내부에 작성한 메서드 가 아니므로 호출되지 않습니다.
이것을 복제하기 위해 서버 호출이 필요하지 않습니다.
const obj = JSON.parse(JSON.stringify(new Template()))
obj.toJSON // undefined
그리고 당신은 그 볼 obj
의 인스턴스가 아닌 Template
. 그것은 단순히 모든 필드를 원래 개체로 Template
인스턴스 로 만든 개체 이지만 해당 클래스의 인스턴스가 아닙니다 .
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다