序列化时仅映射angular类中的现有字段



我正在angular中运行get-web调用:

keydocumentList$ = this.http.get<KeydocumentType[]>(`${config.apiUrl}/api/KeydocumentsType/List`);

Typescript中的keydocumentType类是:

export class KeydocumentType {
keydocumentTypeId: number;

keydocumentCategory: KeydocumentCategory;

keydocumentCategoryId: number;

name: string;
}

但是api给我的数据比我想要的要多,所以串行化的对象看起来像这样:

KeydocumentType {
keydocumentTypeId: 1,
keydocumentCategory: {},
keydocumentCategoryId: 2;
name: "frank",
deleted: false,    //not in the ts class
another: 'blah'    //not in the ts class
}

这让我有些头疼,是否可以告诉JSON忽略ts中不在类中的任何属性?

我知道我可以制作一个视图模型,而不向下传递数据,但有没有办法在前端忽略它。

您可以通过管道将输出映射到对象中。

keydocumentList$ = this.http.get<KeydocumentType[]>(`${config.apiUrl}/api/KeydocumentsType/List`)
.pipe(
map(resp => {
return {
keydocumentTypeId: resp.keydocumentTypeId,
keydocumentCategory: resp.keydocumentCategory,
name: resp.name
}
})
);

如果您有很多这样的客户端视图模型,或者发现自己经常用更多字段更新现有模型,那么一种更自动的方法是创建客户端视图模型的实例并迭代其字段。

keydocumentList$ = this.http.get<KeydocumentType[]>(`${config.apiUrl}/api/KeydocumentsType/List`)
.pipe(
map(resp => {
const model = new KeydocumentType();
for(let prop in model){
model[prop] = resp[prop];
}
return model;
})
);

但是,您需要在TSConfig中禁用noImplicitAny,否则TS编译器将给您一个错误Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'KeydocumentType'.

我认为没有内置的方法。相反,我认为您需要map响应并自己创建模型:

keydocumentList$ = this.http.get<KeydocumentType[]>(`${config.apiUrl}/api/KeydocumentsType/List`)
.map(data => {
const model = new KeydocumentType();
model.keydocumentTypeId = data.keydocumentTypeId;
// And so on
return model;
});

最新更新