1

How to store global variable in Angular2, same with session of PHP?

instead use:

localStorage.setItem();
Nguyen
  • 375
  • 6
  • 18
  • 1
    [`localStorage`](http://stackoverflow.com/questions/8634058/where-the-sessionstorage-and-localstorage-stored) writes to the disk to save the data, just like [session](http://php.net/manual/en/function.session-start.php) for PHP. Angular2 will never write to your disk, so you won't have the same behavior. You will have to use both services and localStorage to take advantage of persistence. – Eric Martinez Mar 17 '16 at 12:18

1 Answers1

8

You could use a shared service for this. To have a unique instance of the service for the whole application, simply define it within the bootstrap function:

bootstrap(AppComponent, [ SharedService ]);

This way, you will be able to set your global variable in it.

export class SomeComponent {
  constructor(private service:SharedService) {
    this.service.someProperty = 'some value';
  }
}

Every elements (components, services) that inject this service will have access to this service.

If you want to be notifed when this field is updated, you could use an observable property as described below:

Community
  • 1
  • 1
Thierry Templier
  • 182,931
  • 35
  • 372
  • 339