TypeScript中的常见对象

时间:2017-01-04 15:15:22

标签: typescript singleton

我正在尝试在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;
}

}

其他页面:

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

1 个答案:

答案 0 :(得分:1)

首先,请看一下:singleton

然后关于您的代码,请执行以下更改:

  1. 从UserDetails类中删除所有实现单例的尝试(_instance静态字段等)
  2. 在UserDetails.ts导出单例实例的末尾,如下所示:
  3. export const DefaultUser = new UserDetails();

    希望这有帮助。