2016-12-12 5 views
5

私はこのクラスを持っている: ativoJSONをWebサービスに送信するときにTypeScriptのエンティティフィールドを無視する方法はありますか。

export class TblColabAdmin { 
    snomatrcompl: string; 
    nflativo: number; 
    ativo: boolean; 
} 

属性は自分のWebサービスエンティティに存在しないので、私はそれがJSONに追加されたことを避けるようにしたいと思います。

例えば、私たちは@ JsonIgnoreアノテーションを持っています。 TypeScriptに似たものが存在しますか?

+1

いいえ、新しいオブジェクトを作成し、送信するプロパティのみを設定する必要があります。 – toskv

+0

'toSSON'メソッドを追加しましたか? 'toJSON(){const obj = Object.assign({}、this)}のようなものです。 obj.ativoを削除します。 objを返します。 } '。または 'toJSON(){Object.assign({}、this、{ativo:undefined})を返します。 } '。 –

+0

この回答に示唆されているようにカスタム置換えを使用すると助かります。 https://stackoverflow.com/a/41685627/2685234 – ramtech

答えて

1

ありません。最も簡単な方法は、送信するプロパティのみを含む新しいオブジェクトを作成することです。例えば

this.http.post('someurl', { 
    snomatrcompl: data.snomatrcompl, 
    nflativo: data.nflativo 
}); 
5

それは、Javaと同じように動作するようにあなたがJsonIgnoredecoratorを作成することができます。

const IGNORE_FIELDS = new Map<string, string[]>(); 
function JsonIgnore(cls: any, name: string) { 
    let clsName = cls.constructor.name; 
    let list: string[]; 

    if (IGNORE_FIELDS.has(clsName)) { 
     list = IGNORE_FIELDS.get(clsName); 
    } else { 
     list = []; 
     IGNORE_FIELDS.set(clsName, list); 
    } 

    list.push(name); 
} 

class Base { 
    toJson(): { [name: string]: any } { 
     let json = {}; 
     let ignore = IGNORE_FIELDS.get(this.constructor.name); 

     Object.getOwnPropertyNames(this).filter(name => ignore.indexOf(name) < 0).forEach(name => { 
      json[name] = this[name]; 
     }); 

     return json; 
    } 
} 

class TblColabAdmin extends Base { 
    snomatrcompl: string; 
    nflativo: number; 

    @JsonIgnore 
    ativo: boolean; 

    constructor(snomatrcompl: string, nflativo: number, ativo: boolean) { 
     super(); 

     this.snomatrcompl = snomatrcompl; 
     this.nflativo = nflativo; 
     this.ativo = ativo; 
    } 
} 

let obj = new TblColabAdmin("str", 43, true).toJson(); 
console.log(obj); // Object {snomatrcompl: "few", nflativo: 43} 

code in playground

をそれは非常に多くのです一度しかやっていなければ動作しますが、コード内でよくある問題なら、アプローチがうまくいくはずです。

+0

これは、使用していない場合にうまく機能しますJSON.stringify、その他の場合には、この記事で提案されているようにReplacerを使用するのが良い方法です。https://stackoverflow.com/questions/41685082/how-to-ignore-properties-sent-via-http/41685627#41685627 – Gabriel

関連する問題