繁体   English   中英

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

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

如何在TypeScript中使用设置器设置对象的每个属性?

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
};

或者,为每个属性设置单独的二传手

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然后可以根据需要更改其属性。

暂无
暂无

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

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