如何在向Web服务发送JSON时忽略TypeScript中的实体字段?

Mar*_*cel 6 json typescript angular

我有这门课:

export class TblColabAdmin {
    snomatrcompl: string;
    nflativo: number;
    ativo: boolean;
}
Run Code Online (Sandbox Code Playgroud)

我的Web服务实体中不存在属性ativo,因此我想避免将其添加到JSON中.

例如,在Java中,我们有@JsonIgnore注释.在TypeScript中是否存在类似的东西?

Nit*_*mer 9

你可以创建一个JsonIgnore 装饰器,使它像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}
Run Code Online (Sandbox Code Playgroud)

(游乐场代码)

如果你只做一次,这是相当多的工作,但如果它是你的代码中的常见问题,那么这种方法应该运行良好.