2017-02-08 3 views
0

TypeScriptのセッターでオブジェクトの各プロパティを設定するにはどうすればよいですか?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'; 

MORE:

ユーザモデル:

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

どうしてエラーですか?また、Userモデルは何ですか? – alebianco

+0

@alebianco更新:私は特定のコードの問題を解決するだけでなく、オブジェクトの小道具をセッターで設定する適切な方法を学びます。 – BenRacicot

+0

上記のコードから 'this._user'が適切に定義されていることは、あなたが間違っていると確信できるエラーを読むことによって明らかではありません。最も重要な部分を省略して、 'コンストラクタ(...){}'は本当に助けにはなりません。 – estus

答えて

1

ヨあなたが呼ぶような各プロパティ

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

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

のための個別のセッターを持って、uがセッターに全体userオブジェクトを渡す必要がありますが、

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

また、ユーザーの他のすべての属性にアクセスする必要があるだろうこのようにして

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

驚くべきことに、 'fname'のようなオブジェクト内の他の小道具は値またはヌルに設定する必要がありますか? – BenRacicot

+0

@BenRacicotは必ずしも必要ではありませんが、最初にユーザーモデルを正しくインスタンス化してから、アプリケーションの実行方法 –

1

エラーメッセージが表示され、存在しないオブジェクトに属性を設定しようとしています。

this.authService.user === nullの場合は、プロパティを設定できません。

まずnew User(...)を作成してthis.authService.userに割り当ててから、必要に応じてプロパティを変更してください。

関連する問題