简体   繁体   English

在angular2(typescript)中遵循模型的最佳实践

[英]Best practice to follow in model in angular2(typescript)

I am working angualar2 application. 我正在使用angualar2应用程序。 In my app I am started creating class for the model instead of interface which has the properties and function which I need on component here is my sample class for user 在我的应用程序中,我开始为模型创建类,而不是为接口创建具有所需组件属性和功能的接口,这是我为用户提供的示例类

class User {
    private name: string;
    private lastName: string;
    constructor(name?: string, lastName?: string) {
        this.name = name || '';
        this.lastName = lastName || '';
    }
    validate() {
        if (!this.name.length) {
            throw 'Please enter name';
        }
        if (!this.lastName.length) {
            throw 'Please enter last name';
        }
    }
};

In given sample class has two property and on the function (it may contains other function like addTiming, calSalary and many other that we need on user) to validate user itself in a model the component I don't need to write code to validate user field and I can use that call everywhere in my app. 在给定的示例类中,具有两个属性,并且在函数上(它可以包含其他函数,例如addTiming,calSalary以及我们需要在用户身上使用的其他函数),以在模型中验证用户本身,该组件不需要编写代码来验证用户字段,我可以在我的应用中的任何地方使用该调用。

But I am not sure is that good practice to have the model like this. 但是我不确定具有这样的模型是否是好的做法。

If form validation is not what you are looking for then try TypeScript decorators - you can make generic validators to use everywhere across your application, supporting DRY this way. 如果不是您需要的表单验证,请尝试使用TypeScript装饰器-您可以使通用验证器在整个应用程序中使用,从而以这种方式支持DRY。 Here is some nice examples: https://github.com/pleerock/class-validator 这是一些很好的例子: https : //github.com/pleerock/class-validator

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM