我正在尝试在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
答案 0 :(得分:1)
首先,请看一下:singleton。
然后关于您的代码,请执行以下更改:
_instance
静态字段等) export const DefaultUser = new UserDetails();
希望这有帮助。