3

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.

Shubham Verma
  • 8,783
  • 6
  • 58
  • 79
  • Use a shared service https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service – Günter Zöchbauer Feb 03 '17 at 07:33
  • In my app. I am using dashboard which is loading once when app is started. But I want to do like, in the dashboard, there is a link "admin " and want show this link when Url would be other than '/admin', but when the URL will be '/admin' then I don't want to show this link. The problem is that Dashboard is loading only once and in the dashboard, *ngIf="adminUrl!='/admin' " value of adminUrl would change on every route change but here (in the dashboard ) value retain same. Please suggest what I can do? – Shubham Verma Feb 03 '17 at 09:05
  • try this https://stackoverflow.com/questions/35985009/angular-2-what-is-equivalent-to-root-scope .A much better solution – Harsha Jayamanna Sep 27 '17 at 17:49

1 Answers1

1

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
Hemant Kumar
  • 140
  • 8