我想正确创建域模型。
我下面的尝试在构造函数外部创建属性。 我应该只在构造函数内创建和设置 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/