2

I am trying to set up a global service which can be accessed through out all the components, precisely I wish to store user related information using this service like roles, name etc. and use it later in all components

I have tried with singleton, but It got clear after browser refresh.

How to achieve this any guidance will be appreciated.

The singleton service is like this:

    export class Principal{
    private isAuthenticated: boolean = false;
    private roles: Array<String>;
    private fullName: String;
    constructor(){} ;
    // getter and setter

}
Arpit
  • 521
  • 2
  • 8
  • 22

2 Answers2

4

You will need to have your service singleton save its state in a browser persistence storage if it is to survive a browser refresh. Add some of your singleton code to your original question and I will update this answer with code that saves its state in sessionStorage;

UPDATE

We can use the angular2-localStorage module to accomplish this.

export class Principal{
    @SessionStorage() private isAuthenticated: boolean = false;
    @SessionStorage() private roles: Array<String>;
    @SessionStorage() private fullName: String;
    constructor(){} ;
    // getter and setter
}

PLEASE NOTE

Do not store any sensitive values here. Your backend API should NOT trust any of these values as the end user can easily change these.

With idomatic typescript you should prefer get and set accessors rather than getter and setter methods.

Martin
  • 15,820
  • 4
  • 47
  • 56
  • How can an end user change these values? – vigamage May 16 '17 at 08:04
  • @vigamage -- in the example given a user could open the debugging console while the app is running and enter `sessionStorage.setItem('roles', 'admin');` to change the values. This is why nothing in the browser should ever be trusted. Just because the Angular app now thinks the user is an `admin` -- the backed API should throw an error when an `admin` API is called. – Martin May 16 '17 at 08:49
  • oh. Thank you for the information. So,, what is the way you suggest to store such data ? – vigamage May 16 '17 at 08:54
  • Store anything like user roles behind an api on the server where it is safe. – Martin May 16 '17 at 19:55
1

This corresponding service provider must be specified when bootstrapping your application or within the providers attribute of the main component.

bootstrap(AppComponent, [ GlobalService ]);

or

@Component({
  (...)
  providers: [ GlobalService ]
})
export class AppComponent {
}

This way all your components will share the same instance of the service.

Thierry Templier
  • 198,364
  • 44
  • 396
  • 360
  • Is there any way to get around having to write `import x from y` at the top of every file also? I'd like to have lodash as a global variable. – GFoley83 Nov 26 '16 at 04:13