如果我尝试使用设置器在TypeScript类中设置属性,它将添加一个属性而不是更改现有属性。该类看起来像
export class User extends Model
{
private username: string;
private firstname: string;
private lastname: string;
// ...
public get Username(): string
{
return this.username;
}
public set Username(value: string)
{
this.username = value;
}
}
如果我通过访问user.Firstname = 'Tobi';
来设置名字,则可以使用console.log(user)
看到该对象现在包含带有大写首字母的Firstname属性。
角度版本:7.3.8
打字稿:3.2.4
NodeJS:11.11.0
浏览器:Firefox 66.0.3和Chrome 73.0.3683.103
操作系统:macOS 10.14.4(18E226)
// Creating a new object
this.userService.create(this.user).subscribe(
(user: User) =>
{
console.log(user);
this.user = user;
}
);
// Trying to update the object
tstUpdateUser()
{
this.user.Firstname = 'Tobi2';
console.log(this.user);
this.userService.update(this.user, this.user.Id).subscribe((user: User) =>
{
this.user = user;
console.log('update', this.user);
});
}
//Output of Dev console in Firefox
{…}
Firstname: "Tobi2"
firstname: "Tobi"
id: 37
...
如果我正确理解了TypeScript的getter和setter,则.Firstname属性应该设置私有的firstname属性,而不是添加Firstname属性。