私はthis exampleのコードに従っていますが、私のtoJSON()関数は呼び出されません。 toJSON以外2を試みることAngular2/4 - toSSON関数をtypescriptクラスに追加する正しい方法は何ですか?
試み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));
を、それが属性にtemplate_itemsは変更されません...私はここで何をしないのですか?
UPDATE
コメントに@estusによって提供さplunkは働いていたので、私は比較することが、角度でものを作ることにしました。 Here it isと動作します。
私が質問を書いたとき、コードを分かりやすくするために、私は 'template_items'に数字の配列を作りました。しかし、私の実際の角度プロジェクトでは、それはカスタムオブジェクトの配列です。 Hereはその構造を示すプランナーです。それも動作します。そしてanother plunkerは角で働いています4.4.6
しかし、この同じ設定は私の角度プロジェクトでは機能しません。ですから、質問は、の誰かがこれを再現することができますか?
私のプロジェクトでは、JSON.stringify()から返された完全に空のオブジェクトを取得します。
それは[template_itemsを変えない](http://plnkr.co/edit/Cv06FG0JAkjAPB5xXORw:
ので、解決策は、両方の機能のreturn文にして直列化インタフェースには、すべてのプロパティを指定することです?p =プレビュー)。 – estus
@Wyatt元の属性が表示されています。 – rmcsharry
@estus私は作品が見えるプランナーに感謝します。今私はそれが私のAngular 4プロジェクトでうまくいかない理由を理解しなければなりません: – rmcsharry