2017-10-20 8 views
0

私は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()から返された完全に空のオブジェクトを取得します。

+0

それは[template_itemsを変えない](http://plnkr.co/edit/Cv06FG0JAkjAPB5xXORw:

ので、解決策は、両方の機能のreturn文にして直列化インタフェースには、すべてのプロパティを指定することです?p =プレビュー)。 – estus

+0

@Wyatt元の属性が表示されています。 – rmcsharry

+0

@estus私は作品が見えるプランナーに感謝します。今私はそれが私のAngular 4プロジェクトでうまくいかない理由を理解しなければなりません: – rmcsharry

答えて

0

だから、私はtoJSON()の動作とどのように文字列置換機能が動作するのか混乱しているようです。

toJSON()を使用すると、指定した項目が返されます。私はすべてのプロパティを返し、関数内で指定したプロパティのみを変更するという印象を受けました。

私のプロジェクトでは、オブジェクトが最初に作成された時点でtemplate_itemsはありませんでした。それは、私のシリアル化されたインターフェイスが指定された唯一のプロパティなので、他のすべてのプロパティが削除されていました。

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> 
} 
関連する問題