How to ignore an object field in TypeScript when sending JSON to a web service?

I have this class:

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

The ativo attribute does not exist in my web service object, so I would like to avoid adding it to JSON.

In Java, for example, there is an @JsonIgnore annotation. Is there something similar in TypeScript?

+5
source share
2 answers

You can create a JsonIgnore decorator to make it work like java:

 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 on the playground )

This is quite a lot of work if you do it only once, but if this is a common problem in your code, then this approach should work well.

+5
source

No. The easiest way is to create a new object containing only those properties that you want to send.

For instance:

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

Source: https://habr.com/ru/post/1261134/


All Articles