打字稿:自动填充 属性 到 getter/setter
Typescript: Autopopulate a property via getter/setter
我有一个 class 用户属性。如果 firstName 和 lastName 已更新,我正在尝试自动填充 'fullname' 属性。但到目前为止,我的代码仅在控制器中手动更新时才填充它。
有没有办法在不显式调用的情况下自动更新 'fullname'?
export class UserDTO {
id: number;
fullname: string;
firstName: string;
lastName: string;
private _fullname string;
get fullname(): string {
return this._fullname;
}
set fullname(value: string) {
this._fullname = this.firstName + (this.lastName ? ' ' + this.lastName : '');
} }
在控制器中的用法:
updatedUser.name = firstName + (lastName ? ' ' + lastName : '');
你的做法全错了。您不需要设置 fullName
.. 并且您当然不需要它的局部变量。
export class UserDTO {
id: number;
firstName: string;
lastName: string;
get fullname(): string {
return this.firstName + (this.lastName ? ' ' + this.lastName : '');
}
}
请求全名时,它将始终是最新的 - 您无法设置它。您可以通过设置 firstName
或 lastName
.
来更新它
我有一个 class 用户属性。如果 firstName 和 lastName 已更新,我正在尝试自动填充 'fullname' 属性。但到目前为止,我的代码仅在控制器中手动更新时才填充它。
有没有办法在不显式调用的情况下自动更新 'fullname'?
export class UserDTO {
id: number;
fullname: string;
firstName: string;
lastName: string;
private _fullname string;
get fullname(): string {
return this._fullname;
}
set fullname(value: string) {
this._fullname = this.firstName + (this.lastName ? ' ' + this.lastName : '');
} }
在控制器中的用法:
updatedUser.name = firstName + (lastName ? ' ' + lastName : '');
你的做法全错了。您不需要设置 fullName
.. 并且您当然不需要它的局部变量。
export class UserDTO {
id: number;
firstName: string;
lastName: string;
get fullname(): string {
return this.firstName + (this.lastName ? ' ' + this.lastName : '');
}
}
请求全名时,它将始终是最新的 - 您无法设置它。您可以通过设置 firstName
或 lastName
.