[英]Angular2/4 - what is the correct way to add a toJSON function to a typescript class?
我遵循了此示例中的代码,但是未调用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
尝试2的相同代码,除了toJSON是:
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));
在所有情况下,它都不会将template_items更改为属性...我在这里缺少什么?
更新
@estus在评论中提供的代码很有效,因此我决定在Angular中进行比较。 在这里 ,它起作用。
当我编写问题时,为了使代码易于理解,我将“ template_items”制成了一个数字数组。 但是在我实际的Angular项目中,它是一组自定义对象。 这是一个显示这种结构的塞子。 它也可以。 另一个在Angular 4.4.6中工作的插件
但是,这种相同的设置在我的Angular项目中不起作用。 因此,问题是万一其他人都可以重现?
在我的项目中,我从JSON.stringify()返回了一个完全空的对象。
因此,似乎我对toJSON()的工作方式和stringify替换函数的工作方式感到困惑。
使用toJSON(),您提供的函数将仅返回您指定的项目。 我的印象是它将返回所有属性,并且仅更改您在函数中指定的属性。
因此,在我的项目中,首次创建对象时没有template_items,并且由于这是我的序列化接口指定的ONLY属性,所有其他属性均被删除,因此为空对象。
因此,解决方案是在函数return语句和serialize接口中都指定ALL属性:
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>
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.