Friday, June 3, 2016

Make current user available through out the ionic2 application

Like every application which have login system in it you have a lot of features available for the user. like if login user is admin then navigation options will change. Along with these there are many situations where you need the current login user like comment feature. So i have pass or fetch from local storage every time i require current login user. I have a different approach login user should be a static variable which is available through out the application.

export class Singleton {
  private static _instance;
  public static get instance() {
    class current_user{
       public login_user: User; 
       public menu_option: Array<{title: string, component: any, icon: string}>;

       retrive_user_from_local_storage(){
        // code to set the current user from local storage.
      }

      populate_menu(){
      // code to populate the menu depending upon the login_user_type.
      }
   }
   if(!Singleton._instance) {
            Singleton._instance = new current_user();
        }

        return Singleton._instance;
    }
 }
}

Now i just have to import file the above file where i require the current user like

import {Singleton} from '../../lib/singleton';

export class BusinessDetail {
  
private singletonObject = Singleton.instance;
//rest code.
}





No comments: