0

I am trying to use a global object in TypeScript. For example, when a remote call is done, the user details gets populated. I would like it to be available throughout the application and be bindable. Can someone point to an example how it can be done?

I am implementing this type of singleton class for the user details class.

User Details:

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;
}

}

Other Page:

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; 
}

Thanks in advance Senthil S

3
  • Have a look here: blog.eexit.net/js-singleton-as-module Commented Jan 4, 2017 at 15:22
  • @Amid - I thought that is what I am doing in my type script class. The example is in java script, so when I do the same in type script, it does not work as I wanted. Am I missing something? Commented Jan 4, 2017 at 17:05
  • No exactly. See my post as answer. Commented Jan 4, 2017 at 17:57

1 Answer 1

1

First off, have a look here: singleton.

Then regarding your code, do the following changes:

  1. Remove all attempts to implement singleton from UserDetails class ( _instance static field and so on)
  2. In the end of the UserDetails.ts export singleton instance like this:

export const DefaultUser = new UserDetails();

Hope this helps.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot @Amid. Excellent. I started using static variables which also works for my case but I like this way to be consistent with the type script modules.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.