2017-02-08 76 views
0

如何在TypeScript中使用setter設置對象的每個屬性?如何使用setter和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

+0

所以......錯誤是什麼?另外,什麼是用戶模型? – alebianco

+0

@alebianco更新:我不只是想解決我的具體代碼問題,而是學習用setter設置對象道具的正確方法。 – BenRacicot

+0

從上面的代碼中可以看出'this._user'已被正確定義,通過讀取錯誤可以確定它不是。省略最重要的部分,'constructor(...){}',並沒有真正的幫助。 – estus

回答

1

呦u需要整個user對象傳遞給二傳手,但你需要訪問該用戶的所有其他屬性

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'; 
+0

太棒了,所以對象中的其他道具,比如'fname'必須設置爲一個值或null? – BenRacicot

+0

@BenRacicot不一定,但你需要確保你先正確地實例化用戶模型,然後這一切都取決於你希望你的應用程序執行的方式 –

1

錯誤消息似乎很明顯,您試圖在不存在的對象上設置屬性。

if this.authService.user === null你不能設置它的屬性。

您首先要在某處創建new User(...)並將其指定給this.authService.user,然後您可以根據需要更改其屬性。