我目前正在开发一个Angular 2应用程序.在开发过程中,我开始使用TypeScript类从
JSON创建对象,我通过HTTP或在表单中创建新对象时创建对象.
例如,该类可能看起来像这样.
export class Product { public id: number; public name: string; public description: string; public price: number; private _imageId: number; private _imageUrl: string; constructor(obj: Object = {}) { Object.assign(this,obj); } get imageId(): number { return this._imageId; } set imageId(id: number) { this._imageId = id; this._imageUrl = `//www.example.org/images/${id}`; } get imageUrl(): string { return this._imageUrl; } public getDTO() { return { name: this.name,description: this.description,imageId: this.imageId,price: this.price } } }
到目前为止,上面显示的这个解决方但现在让我们假设对象中有更多属性,我想要一个干净的DTO(例如没有私有属性),通过POST将此Object发送到我的服务器.一个更通用的getDTO()函数怎么样?我想避免列出很长的财产分配清单.我在考虑为属性使用装饰器.但我真的不知道如何使用它们来过滤DTO的属性.
解决方法
您可以使用
property decorator:
const DOT_INCLUDES = {}; function DtoInclude(proto,name) { const key = proto.constructor.name; if (DOT_INCLUDES[key]) { DOT_INCLUDES[key].push(name); } else { DOT_INCLUDES[key] = [name]; } } class A { @DtoInclude public x: number; public y: number; @DtoInclude private str: string; constructor(x: number,y: number,str: string) { this.x = x; this.y = y; this.str = str; } toDTO(): any { const includes: string[] = DOT_INCLUDES[(this.constructor as any).name]; const dto = {}; for (let key in this) { if (includes.indexOf(key) >= 0) { dto[key] = this[key]; } } return dto; } } let a = new A(1,2,"string"); console.log(a.toDTO()); // Object {x: 1,str: "string"}
如果需要,可以使用在他们的示例中使用的the reflect-metadata,我使用DOT_INCLUDES注册表实现它,以便它可以在操场中很好地工作而无需额外的依赖项.
编辑
正如@Bergi评论的那样,您可以迭代包含而不是:
toDTO(): any { const includes: string[] = DOT_INCLUDES[(this.constructor as any).name]; const dto = {}; for (let ket of includes) { dto[key] = this[key]; } return dto; }
这确实更有效,更有意义.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。