【问题标题】:Typescript: Autopopulate a property via getter/setter打字稿:通过 getter/setter 自动填充属性
【发布时间】:2017-11-10 13:04:54
【问题描述】:

我有一个用户属性类。如果更新了名字和姓氏,我正在尝试自动填充“全名”属性。但到目前为止,我的代码仅在控制器中手动更新时才会填充它。

有没有办法在不显式调用的情况下自动更新“全名”?

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

【问题讨论】:

    标签: typescript getter-setter


    【解决方案1】:

    这一切都错了。你不需要设置fullName.. 你当然也不需要一个局部变量。

    export class UserDTO {
        id: number;
        firstName: string;
        lastName: string;
    
        get fullname(): string {
            return this.firstName + (this.lastName ? ' ' + this.lastName : '');
        }
    }
    

    请求全名时,它始终是最新的 - 您无法设置它。您可以通过设置firstName 或lastName 来更新它。

    【讨论】:

      猜你喜欢
      • 2017-06-02
      • 2019-04-20
      • 2016-04-07
      • 1970-01-01
      • 2014-09-05
      • 1970-01-01
      • 2011-01-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多