Angularjs   发布时间:2022-04-20  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了TypeScript/Angular2中的DTO设计大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我目前正在开发一个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"}

(code in playground)

如果需要,可以使用在他们的示例中使用的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;
}

这确实更有效,更有意义.

大佬总结

以上是大佬教程为你收集整理的TypeScript/Angular2中的DTO设计全部内容,希望文章能够帮你解决TypeScript/Angular2中的DTO设计所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。