javascript - 如何正确创建 Angular 域模型

标签 javascript angular typescript oop

我想正确创建域模型。

我下面的尝试在构造函数外部创建属性。 我应该只在构造函数内创建和设置 TestModel 类的属性吗?这样他们的代码行就会更少

我有以下我认为正确的尝试:

export class TestModel1 {
  public currentPage: number = 0;
  public hasNext: boolean = false;
  public hasPrev: boolean = false;
  public pageSize: number = 0;
  public totalItems: number = 0;

  constructor(data: any) {
      this.currentPage = data.currentPage;
      this.hasNext = data.hasNext;
      this.hasPrev = data.hasPrev;
      this.pageSize = data.pageSize;
      this.totalItems = data.totalItems;
  }
}

看起来有点大,代码行太多。

目前我需要传入一个数据对象,然后进行映射。 他们是我使用构造函数更好地实现这一点的聪明方法吗?

最佳答案

如果我们谈论模型类,其声明应如下例所示:

export class Account {
    constructor(
        public activated: boolean,
        public authorities: string[],
        public email: string,
        public firstName: string,
        public langKey: string,
        public lastName: string,
        public login: string,
        public imageUrl: string
    ) {}
}

当然,您不应该在构造函数之外定义值。您可以像示例中那样声明模型类成员,但没有值的定义:

export class TestModel1 {
  public currentPage: number;
  public hasNext: boolean;
  public hasPrev: boolean;
  public pageSize: number;
  public totalItems: number;

  constructor(data: any = null) {
    if(data !== null) {
      this.currentPage = data.currentPage;
      this.hasNext = data.hasNext;
      this.hasPrev = data.hasPrev;
      this.pageSize = data.pageSize;
      this.totalItems = data.totalItems;
    }
  }
}

如果您想声明默认值,我的建议是在构造函数内执行此操作,以获得干净且良好的代码。

更新:

export class TestModel1 {
  public currentPage: number;
  public hasNext: boolean;
  public hasPrev: boolean;
  public pageSize: number;
  public totalItems: number;

  constructor(data: any = null) {
    if(data !== null) {
      this.currentPage = data.currentPage;
      this.hasNext = data.hasNext;
      this.hasPrev = data.hasPrev;
      this.pageSize = data.pageSize;
      this.totalItems = data.totalItems;
    }
    else {
      this.currentPage = 0;
      this.hasNext = false;
      this.hasPrev = false;
      this.pageSize = 0;
      this.totalItems = 0;
    }
  }
}

如果你想有默认值那就更好了

关于javascript - 如何正确创建 Angular 域模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51301940/

相关文章:

javascript - 返回无效 0;与返回;

javascript - 将 getElementsByClassName 放入 getElementByID 中

angular - 使用 Angular 4 时 ngModule 的问题

http - angular2 等待错误 http 响应

typescript - 为什么类似的代码在 TypeScript 中会产生不同的错误?

javascript - 无法在 Plnkr 中加载 app.component.html

javascript - 当我们在 google map api 中获取坐标时,如何显示移动的人的方向箭头

angular - 如何选择手动选择的选项?

javascript - typescript 数组声明是否需要展开/休息运算符?

angular - 无法捕获错误