如何使用 setter 和 getter 在 TypeScript 中正确设置对象属性?

How to properly set object properties in TypeScript with setters and getters?

如何在 TypeScript 中设置带有 setter 的对象的每个 属性?

export class AuthService {
    private _user:User; // User is my model

    constructor(...){}

    public get user()
    {
        return this._user;
    }

    public set user(value){
        this._user = value;
    }
...

然后在任何地方设置都会出错:

this.authService.user.id = data.userId;
this.authService.user.isLoggedIn = 'true';

更多:

用户模型:

export class User {
    constructor(
        public email: string,
        public pass: string, 
        public id?: string,
        public fname?: string,
        public lname?: string,
        public isLoggedIn?: string){}
}

错误:Cannot set property 'id' of undefined

您需要将整个 user 对象传递给 setter,但您需要访问用户的所有其他属性

this.authService.user = {
    id: data.userId,
    isLoggedIn: true
};

或者,每个 属性

有单独的 setter
public set id(value){
    this._user.id = value;
}

public set isLoggedIn(value){
    this._user.isLoggedIn = value;
}

你会这样称呼

this.authService.id = data.userId;
this.authService.isLoggedIn = 'true';

错误消息似乎很清楚,您正在尝试为不存在的对象设置属性。

如果this.authService.user === null您无法设置它的属性。

您必须先在某处创建一个 new User(...) 并将其分配给 this.authService.user 然后您可以根据需要更改它的属性。