2017-01-04 5 views
0

TypeScriptでグローバルオブジェクトを使用しようとしています。たとえば、リモート呼び出しが完了すると、ユーザーの詳細が入力されます。私はそれがアプリケーション全体で利用可能でバインド可能であることを望みます。誰かが例を指し示すことができますか?TypeScriptの共通オブジェクト

私はこのタイプのシングルトンクラスをユーザーの詳細クラスに実装しています。

ユーザーの詳細:

export class UserDetails { 
//Gets populated for all the remote calls 
userGuid: string; 
firstName: string; 
lastName: string; 
fullName: string; 
isAuthenticated: boolean; 

private static _instance: UserDetails = new UserDetails(); 
constructor() { 
    if (UserDetails._instance) { 
     throw new Error("Error: Instantiation failed: Use UserDetails.User instead of new."); 
    } 
    UserDetails._instance = this; 
} 

public static get User(): UserDetails { 
    return UserDetails._instance; 
} 

@computedFrom('fullName') 
get FullName(): string { 
    return this.fullName; 
} 

}

その他のページ:singleton:事前に

import {UserDetails} from 'models/userDetails'; 
export class Home { 
    /*@bindable*/router: Router; 
    //This does not have the values 
    //that gets populated after every remote call to the server 
    userDetails = UserDetails.User; 
} 

おかげ SenthilさんS

+0

ここをクリックしてください:http://blog.eexit.net/js-singleton-as-module/ – Amid

+0

@Amid - 私は自分のタイプのスクリプトクラスでやっていると思っています。この例はJavaスクリプトに書かれているので、同じタイプのスクリプトでは、私が望むように動作しません。何か不足していますか? –

+0

正確にはありません。私のポストを答えとして見てください。 – Amid

答えて

1

まず第一には、ここを見てください。 UserDetails.ts輸出シングルトンの終わりには、すべてのUserDetailsクラスからシングルトンを実装しようとする試み(_instance静的フィールドとその上を)外し

  1. :あなたのコードについて次に

    、以下の変更を行いますこのような場合:

export const DefaultUser = new UserDetails();

は、この情報がお役に立てば幸いです。

+0

ありがとう@Amid。優れた。私は私のケースでも動作する静的変数を使用し始めましたが、私はこのようにして、スクリプトモジュールと一貫しています。 –

関連する問題