I am creating a demo app in Angular 2 and I stuck in this app. I want to use a global variable/object throughout the app like $rootScope in angular. Please suggest me what to do to achieve this?
Currently, I am using EventEmitter.
app.component.ts:
<a routerLink="/admin" routerLinkActive="active" style="float:right;"
*ngIf="currentUrl != '/admin'" (adminUrl)="setUrl($event)" >Admin-{{currentUrl}}</a>
`@Output() adminUrl:String;`
heroes.component.ts:
@Output() adminUrl = new EventEmitter();
this.adminUrl.emit(this.router.location.path());
The above code is not all code, this is for understanding that what I am doing to achieve for the same.
you can use localStraogeService to use a global variable/object throughout the app first of all you have to install localStorage in your project by
npm install angular-2-local-storage
then import it into your baseComponent if you have
import { LocalStorageService } from 'angular-2-local-storage';
then just inject in the constructor of BaseComponent
constructor(protected localStorageService: LocalStorageService)
then you can get and set the value of localStorageService by
this.localStorageService.set('sessionData',{Object});
and get by
this.seesionDetails = this.localStorageService.get('sessionData');
you can also follow the things from the below link to achieve localStorageServices
https://www.npmjs.com/package/angular-2-local-storage
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With