【问题标题】:Best practice to follow in model in angular2(typescript)在 angular2(typescript) 中遵循模型的最佳实践
【发布时间】:2016-12-26 06:23:08
【问题描述】:

我正在使用 angualar2 应用程序。在我的应用程序中,我开始为模型创建类而不是接口,该接口具有我在组件上需要的属性和功能,这是我的用户示例类

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';
        }
    }
};

在给定的示例类中,有两个属性和函数(它可能包含其他函数,如 addTiming、calSalary 和我们需要的许多其他函数),以在模型中验证用户本身,组件 I不需要编写代码来验证用户字段,我可以在我的应用程序的任何地方使用该调用。

但我不确定拥有这样的模型是否是一种好习惯。

【问题讨论】:

    标签: class angular model-view-controller model


    【解决方案1】:

    如果表单验证不是您想要的,那么试试 TypeScript 装饰器 - 您可以让通用验证器在您的应用程序中随处使用,以这种方式支持 DRY。 这里有一些很好的例子:https://github.com/pleerock/class-validator

    【讨论】:

    • 它不仅仅是我将要验证的功能以及我需要用户的许多其他功能
    猜你喜欢
    • 1970-01-01
    • 2010-09-25
    • 2016-10-05
    • 2018-04-23
    • 2012-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-16
    相关资源
    最近更新 更多