I am building an Angular 2 based app. I want to have a global variable that can be accessed and also modified by all components. All current answers I am able to find are for constants. Can anyone suggest how I can do so ? Thanks!
Asked
Active
Viewed 675 times
-1
-
1I believe a shared service would be the way to go: https://angular.io/guide/component-interaction – AT82 Jun 30 '17 at 08:32
-
Does [this question](https://stackoverflow.com/questions/11938380/global-variables-in-angularjs) answer your question? – JiFus Jun 30 '17 at 08:32
-
To start with, are you sure it is a good idea to have global variables at all? – helcim Jun 30 '17 at 08:32
-
I have a http request that is fired off every 5 minutes. I need a global variable to turn it off if the user clicks on the unsubscribe button – AP01 Jun 30 '17 at 08:33
-
if the flag value can be changed across many components, than yeah, a singletone service approach would be the best – Jota.Toledo Jun 30 '17 at 08:36
-
You still can put it in `environment.ts` – Jun 30 '17 at 08:42
-
@Jota.Toledo the value doesnt stay changed across multiple components – AP01 Jun 30 '17 at 09:07
-
doesnt stay changed? what do you mean? – Jota.Toledo Jun 30 '17 at 09:23
1 Answers
1
When I have to deal with global variable I usually do it via shared services. I declare a variable in root component's service, which is usually app.service.ts
and make it available to other components via setter and getter functions.
To demonstrate, I used a heroes tutorial plunker that has three components. In the app.service.ts
I declared a variable myGlobalVar
.
I added buttons in all other components to change the value of myGlobalVar
and lookup it's value at anytime.
You can find interaction details from this example
app.service.ts:
@Injectable()
export class AppService{
myGlobalVar;
constructor(){
this.myGlobalVar = true;
console.log("My global variable value: " + this.myGlobalVar);
alert("My intial global variable value is: " + this.myGlobalVar);
}
setMyGV(val: boolean){
console.log("Setting FV to: " + val);
this.myGlobalVar = val;
}
getMyGV(val: boolean){
return this.myGlobalVar;
}
}
Accessing and modifying the variable from a component:
export class exampleComponent{
constructor(private appService: AppService) {}
changeGV(val){
this.appService.setMyGV(val);
}
showGV(){
alert("GV: " + this.appService.getMyGV());
}
}

Nehal
- 13,130
- 4
- 43
- 59