简体   繁体   English

打字稿:通过getter / setter自动填充属性

[英]Typescript: Autopopulate a property via getter/setter

I have a class for User Properties. 我有一个用于用户属性的类。 I'm trying to auto-populate the 'fullname' property if firstName and lastName is updated. 如果firstName和lastName已更新,我正在尝试自动填充'fullname'属性。 But so far, my code only populate it when it is updated manually by in the controller. 但是到目前为止,我的代码仅在由控制器手动更新时填充。

Is there a way to auto-update the 'fullname' without explicitly calling it? 有没有一种方法可以自动更新“全名”而无需显式调用它?

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

Usage in controller: 控制器中的用法:

updatedUser.name = firstName + (lastName ? ' ' + lastName : '');

You're going about this all wrong. 您要解决所有这些错误。 You don't need to set fullName .. and you certainly don't need a local variable for it. 您不需要设置fullName ..并且您当然不需要本地变量。

export class UserDTO {
    id: number;
    firstName: string;
    lastName: string;

    get fullname(): string {
        return this.firstName + (this.lastName ? ' ' + this.lastName : '');
    }
}

When requesting fullname, it will always be up to date - and you cannot set it. 请求全名时,它始终是最新的-您无法设置。 You update it by setting firstName or lastName . 您可以通过设置firstNamelastName更新它。

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

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