# Global variables on ionic 2

**URL:** <https://forum.ionicframework.com/t/global-variables-on-ionic-2/45890>\
**Category:** ionic-v3\
**Created:** [March 9, 2016, 8:52am UTC](https://forum.ionicframework.com/t/global-variables-on-ionic-2/45890 "2016-03-09T08:52:03Z")\
**Posts on this page:** 20\
**Page:** 1

<div class="post-metadata">

**Author:** ![MrBokeh](https://avatars.discourse-cdn.com/v4/letter/m/ec9cab/32.png) [@MrBokeh](https://forum.ionicframework.com/u/MrBokeh)\
**Post date:** [March 9, 2016, 8:52am UTC](https://forum.ionicframework.com/t/global-variables-on-ionic-2/45890/1 "2016-03-09T08:52:03Z")

</div>

How can i use global variables on ionic 2?  
Which can be access anywhere between pages and the views like on ionic 1.

---

<div class="post-metadata">

**Author:** ![lhteam](https://avatars.discourse-cdn.com/v4/letter/l/bc8723/32.png) [@lhteam](https://forum.ionicframework.com/u/lhteam)\
**Post date:** [March 9, 2016, 9:12am UTC](https://forum.ionicframework.com/t/global-variables-on-ionic-2/45890/2 "2016-03-09T09:12:13Z")

</div>

declare var socket: any;

```auto
import {App,Page, IonicApp, Platform, Storage, SqlStorage} from 'ionic/ionic';
@App({
  templateUrl: 'build/app.html'
})

```

Edit app.js .  
declare socket var on top . You can access “socket” variable in other pages .

---

<div class="post-metadata">

**Author:** ![kuntal](https://avatars.discourse-cdn.com/v4/letter/k/bcef8e/32.png) [@kuntal](https://forum.ionicframework.com/u/kuntal)\
**Post date:** [March 9, 2016, 9:24am UTC](https://forum.ionicframework.com/t/global-variables-on-ionic-2/45890/3 "2016-03-09T09:24:24Z")

</div>

This is the only way to declare global variable? if I have 10 global var of different types then I have to declare all variable one after another at app.ts?

---

<div class="post-metadata">

**Author:** ![lhteam](https://avatars.discourse-cdn.com/v4/letter/l/bc8723/32.png) [@lhteam](https://forum.ionicframework.com/u/lhteam)\
**Post date:** [March 9, 2016, 9:39am UTC](https://forum.ionicframework.com/t/global-variables-on-ionic-2/45890/4 "2016-03-09T09:39:28Z")

</div>

declare var socket: any;  
declare var push: any;  
declare var username: any;  
import {App,Page, IonicApp, Platform, Storage, SqlStorage} from ‘ionic/ionic’;  
@App({  
templateUrl: ‘build/app.html’  
})

---

<div class="post-metadata">

**Author:** ![richardshergold](https://sea1.discourse-cdn.com/ionicframework/user_avatar/forum.ionicframework.com/richardshergold/32/91823_2.png) [@richardshergold](https://forum.ionicframework.com/u/richardshergold)\
**Post date:** [March 9, 2016, 9:55am UTC](https://forum.ionicframework.com/t/global-variables-on-ionic-2/45890/5 "2016-03-09T09:55:37Z")

</div>

I think it depends on what you want to do really but take a look at the Conference app [here](https://github.com/driftyco/ionic-conference-app/blob/master/app/providers/user-data.js) and have a look at how the **favourites** variable is maintained in there with getters and setters etc and shared across multiple components using the **user-data** provider.

---

<div class="post-metadata">

**Author:** ![luchillo17](https://sea1.discourse-cdn.com/ionicframework/user_avatar/forum.ionicframework.com/luchillo17/32/78209_2.png) [@luchillo17](https://forum.ionicframework.com/u/luchillo17)\
**Post date:** [March 9, 2016, 1:34pm UTC](https://forum.ionicframework.com/t/global-variables-on-ionic-2/45890/6 "2016-03-09T13:34:28Z")

</div>

Well… if using webpack you could declare them from the `webpack.config.js` but then you would be tied to webpack until you declare those variables in your code, also it’s not a recommended way of doing it since those variables definition would be in the config of the build process and not in your source code, which makes way harder to understand the code since you can’t tell where the hell those variables come from unless you’re the one that made the variables, tough is a good step for polyfills and libraries that need global scope like Chart.js.

---

<div class="post-metadata">

**Author:** ![mhartington](https://sea1.discourse-cdn.com/ionicframework/user_avatar/forum.ionicframework.com/mhartington/32/137757_2.png) [@mhartington](https://forum.ionicframework.com/u/mhartington)\
**Post date:** [March 9, 2016, 9:07pm UTC](https://forum.ionicframework.com/t/global-variables-on-ionic-2/45890/7 "2016-03-09T21:07:47Z")

</div>

In Ionic 2, we have ES6 modules, and having global variables isn’t really recommended. In fact, it’s big anti-pattern with modules

@richardshergold is pointing you in the right direction. Having a dedicated data-store class instead is what you should be doing. This keeps things nice and separated and you can reason about where things are coming from.

---

<div class="post-metadata">

**Author:** ![ultradryan](https://sea1.discourse-cdn.com/ionicframework/user_avatar/forum.ionicframework.com/ultradryan/32/101819_2.png) [@ultradryan](https://forum.ionicframework.com/u/ultradryan)\
**Post date:** [July 22, 2016, 10:49pm UTC](https://forum.ionicframework.com/t/global-variables-on-ionic-2/45890/8 "2016-07-22T22:49:59Z")

</div>

> [@lhteam](#):
>
> @App({templateUrl: ‘build/app.html’})

Hi am really getting an headache on trying to understand how global variable works in ionic 2 … or how we achieve the same thing.

I read on stackoverflow that some suggest different ways becuz Angular 2 syntax is somehow changing recently, I also read, some mention BehaviorSubject… but I dun understand how it works… or does it work in ionic 2.

> <https://stackoverflow.com/questions/34376854/delegation-eventemitter-or-observable-in-angular/35568924#35568924>

I come to realise there’s nothing like $rootScope anymore in ionic2, but I still cant manage to understand how.

1. Say, I was trying to use ngSwitch to cater an app with mutliple language.
2. I register a service to detect User Language on default (while allowing them to change it in a dropdown menu).
3. in ionic 1 I just do the detection at the beginning and store it to a variable in the rootScope, users may change and alter the variable.
4. ngSwitch will watch the variable and switch language content (for some reason my users need to be able to switch the language anytime quickly).

so… how do I do this in ionic2? declaring variable in the app.ts doesnt work… I tried… 😥

---

<div class="post-metadata">

**Author:** ![ultradryan](https://sea1.discourse-cdn.com/ionicframework/user_avatar/forum.ionicframework.com/ultradryan/32/101819_2.png) [@ultradryan](https://forum.ionicframework.com/u/ultradryan)\
**Post date:** [July 22, 2016, 10:51pm UTC](https://forum.ionicframework.com/t/global-variables-on-ionic-2/45890/9 "2016-07-22T22:51:35Z")

</div>

Hi am really getting an headache on trying to understand how global variable works in ionic 2 … or how we achieve the same thing.

I read on stackoverflow that some suggest different ways becuz Angular 2 syntax is somehow changing recently, I also read, some mention BehaviorSubject… but I dun understand how it works… or does it work in ionic 2.

> <https://stackoverflow.com/questions/34376854/delegation-eventemitter-or-observable-in-angular/35568924#35568924>

I come to realise there’s nothing like $rootScope anymore in ionic2, but I still cant manage to understand how.

1. Say, I was trying to use ngSwitch to cater an app with mutliple language.
2. I register a service to detect User Language on default (while allowing them to change it in a dropdown menu).
3. in ionic 1 I just do the detection at the beginning and store it to a variable in the rootScope, users may change and alter the variable.
4. ngSwitch will watch the variable and switch language content (for some reason my users need to be able to switch the language anytime quickly).

so… how do I do this in ionic2? declaring variable in the app.ts doesnt work… I tried… 😥

---

<div class="post-metadata">

**Author:** ![rapropos](https://sea1.discourse-cdn.com/ionicframework/user_avatar/forum.ionicframework.com/rapropos/32/100227_2.png) [@rapropos](https://forum.ionicframework.com/u/rapropos)\
**Post date:** [July 22, 2016, 10:51pm UTC](https://forum.ionicframework.com/t/global-variables-on-ionic-2/45890/10 "2016-07-22T22:51:59Z")

</div>

Look at [ng2-translate](https://github.com/ocombe/ng2-translate). There is an Ionic sample in the README.

---

<div class="post-metadata">

**Author:** ![ultradryan](https://sea1.discourse-cdn.com/ionicframework/user_avatar/forum.ionicframework.com/ultradryan/32/101819_2.png) [@ultradryan](https://forum.ionicframework.com/u/ultradryan)\
**Post date:** [July 22, 2016, 11:09pm UTC](https://forum.ionicframework.com/t/global-variables-on-ionic-2/45890/11 "2016-07-22T23:09:09Z")

</div>

thanks @rapropos I will try to make sense of that.

It looks promising on creating some mutli-language app.  
However I am using multiple JSON to load some sort of complicated ancient text content to the view…  
It is hard to explain, but it seems a bit different from just switching between language.😭  
I really need NgSwitch to get working to solve the problem in the simplest manner. 🤔

So I really really really… want to know how to get it working, to store and change a variable and bind it with content.

---

<div class="post-metadata">

**Author:** ![rapropos](https://sea1.discourse-cdn.com/ionicframework/user_avatar/forum.ionicframework.com/rapropos/32/100227_2.png) [@rapropos](https://forum.ionicframework.com/u/rapropos)\
**Post date:** [July 22, 2016, 11:18pm UTC](https://forum.ionicframework.com/t/global-variables-on-ionic-2/45890/12 "2016-07-22T23:18:27Z")

</div>

@richardshergold covered that upthread with links to exactly where to look in the conference app.

---

<div class="post-metadata">

**Author:** ![doron](https://sea1.discourse-cdn.com/ionicframework/user_avatar/forum.ionicframework.com/doron/32/99363_2.png) [@doron](https://forum.ionicframework.com/u/doron)\
**Post date:** [July 23, 2016, 8:50pm UTC](https://forum.ionicframework.com/t/global-variables-on-ionic-2/45890/13 "2016-07-23T20:50:52Z")

</div>

How about storing your globals in a singleton class? As in:

- make a module for your globals, have it contain one class that has all the “globals” you need.
- use the class as a singleton by decorating it with `@Injectable` and including it in `app.ts` and in its `ionicBootstrap()` call
- include the class anywhere you need a global

Done!

---

<div class="post-metadata">

**Author:** ![ultradryan](https://sea1.discourse-cdn.com/ionicframework/user_avatar/forum.ionicframework.com/ultradryan/32/101819_2.png) [@ultradryan](https://forum.ionicframework.com/u/ultradryan)\
**Post date:** [July 24, 2016, 3:22am UTC](https://forum.ionicframework.com/t/global-variables-on-ionic-2/45890/14 "2016-07-24T03:22:46Z")

</div>

Thanks @doron  
I was sort of trying to achieve it in a similar way by setting up a “globals” class/service with Injectable.

Then, I face a problem, while the variables are being updated, the changes were not known real-time by other component. I ended up using an “emit” function to get it done by triggering an event.

Not sure if this is the proper way of doing it, but it worked.

---

<div class="post-metadata">

**Author:** ![doron](https://sea1.discourse-cdn.com/ionicframework/user_avatar/forum.ionicframework.com/doron/32/99363_2.png) [@doron](https://forum.ionicframework.com/u/doron)\
**Post date:** [July 27, 2016, 1:04am UTC](https://forum.ionicframework.com/t/global-variables-on-ionic-2/45890/15 "2016-07-27T01:04:30Z")

</div>

Yes, @ultradryan, that’s exactly what I was suggesting. I also used this (injectable provider class) solution and had the same problem - that some variables were not being detected as changed.

That turned out to be related to zone.js and angular2 change detection.

One (probably terrible) hack that solved things and always worked for me was to set the variable inside a `setTimeout()` (or similar) call because that triggers the angular2 change detection. So I did:

In the provider, injectable class that provides a variable’s value to another:

instead of this:

```
this.memberVariable = value;

```

i had this:

```
setTimeout(this.memberVariable = value);

```

and the change-detection issue went away.

I think this is a hack and at some point I’ll look more into improving on it because I dislike hacks, but it works.

---

<div class="post-metadata">

**Author:** ![cybercoder](https://avatars.discourse-cdn.com/v4/letter/c/57b2e6/32.png) [@cybercoder](https://forum.ionicframework.com/u/cybercoder)\
**Post date:** [September 13, 2016, 7:46am UTC](https://forum.ionicframework.com/t/global-variables-on-ionic-2/45890/16 "2016-09-13T07:46:04Z")

</div>

I used this method for access to host variable via provider e.g.

in app.ts top

declare var host : ‘[http://xxx](http://xxx)’ ;

in provider class :  
this.http.get(host+’/api/r/lst’)

But : TypeScript error: path Error TS2304: Cannot find name ‘host’.

---

<div class="post-metadata">

**Author:** ![LouisR](https://avatars.discourse-cdn.com/v4/letter/l/9de053/32.png) [@LouisR](https://forum.ionicframework.com/u/LouisR)\
**Post date:** [March 24, 2017, 8:34pm UTC](https://forum.ionicframework.com/t/global-variables-on-ionic-2/45890/17 "2017-03-24T20:34:07Z")

</div>

@mhartington @richardshergold can you help us (newbies) create ‘best practice’ once and for all to manage global variables in ionic 2? (I know I’m bumping the thread but it’s worth it).

I checked the Conference App as suggested by @richardshergold and looked up the “ **favorites** ” variable (not favourites you made a typo 😉 ). And there seem to be a **user-data** provider in the user-data.ts file.

So I did my own provider:

global-vars.ts:

```
import { Injectable } from '@angular/core';
import { Events } from 'ionic-angular';
import { Storage } from '@ionic/storage';

  @Injectable()
  export class GlobalVars {

  	_vars: Array<{name: string, value: any}>;

  	constructor(
  		public events: Events,
  		public storage: Storage,
	) {
  		console.log('Hello GlobalVars Provider');
  	}

  	varExist(varName: string): boolean {
   		return (this._vars.indexOf(varName) > -1);
  	};

  	addGlobalVar(varName: string, value: any): void {
  		this._vars.push({
		  name: varName,
		  value: value
		});
  	};

  	removeGlobalVar(varName: string): void {
  		let index = this._vars.indexOf(varName);
  		if (index > -1) {
  			this._vars.splice(index, 1);
  		}
  	};

  }

```

and in a component,  
weightlevel.ts:

```
import { Component } from '@angular/core';
import { NavController, NavParams } from 'ionic-angular';
import { ComparePage } from '../compare/compare';
import { ViewChild } from '@angular/core';
import { Slides } from 'ionic-angular';
import { LocalStorageService } from 'angular-2-local-storage';
import { GlobalVars } from '../../providers/global-vars';

@Component({
    selector: 'page-weightlevel',
    templateUrl: 'weightlevel.html'
})
export class WeightlevelPage {

    name: string;

    constructor(
        public navCtrl: NavController,
        public navParams: NavParams,
        private localStorageService: LocalStorageService,
        public globalVars: GlobalVars,
    ) {
        console.log("Executing Weightlevel.ts");
        this.name = 'Max';
        this.globalVars.addGlobalVar("isWebIntegration", false);
    }

    @ViewChild(Slides) slides: Slides;

    ionViewDidLoad() {
        console.log('ionViewDidLoad WeightlevelPage');
    }

    goToSlide() {
        this.slides.slideTo(2, 500);
    }
}

```

Can you help me finish this code? It’s not working for now.

Thanks

---

<div class="post-metadata">

**Author:** ![rapropos](https://sea1.discourse-cdn.com/ionicframework/user_avatar/forum.ionicframework.com/rapropos/32/100227_2.png) [@rapropos](https://forum.ionicframework.com/u/rapropos)\
**Post date:** [March 24, 2017, 10:11pm UTC](https://forum.ionicframework.com/t/global-variables-on-ionic-2/45890/18 "2017-03-24T22:11:51Z")

</div>

I think this approach is overly generic, and loses you lots of important compile-time checking, IDE assistance, and self-documentation. If you have a global `isWebIntegration` boolean, say so. Explicitly put `isWebIntegration: boolean` in your provider (or expose something that provides a `Promise<boolean>` if you wish it to be seamlessly integrated with backing storage).

---

<div class="post-metadata">

**Author:** ![LouisR](https://avatars.discourse-cdn.com/v4/letter/l/9de053/32.png) [@LouisR](https://forum.ionicframework.com/u/LouisR)\
**Post date:** [March 25, 2017, 1:32am UTC](https://forum.ionicframework.com/t/global-variables-on-ionic-2/45890/19 "2017-03-25T01:32:39Z")

</div>

I am not sure I get what you say. Can you code it ?

---

<div class="post-metadata">

**Author:** ![rapropos](https://sea1.discourse-cdn.com/ionicframework/user_avatar/forum.ionicframework.com/rapropos/32/100227_2.png) [@rapropos](https://forum.ionicframework.com/u/rapropos)\
**Post date:** [March 25, 2017, 5:02am UTC](https://forum.ionicframework.com/t/global-variables-on-ionic-2/45890/20 "2017-03-25T05:02:42Z")

</div>

> [@LouisR](#):
>
> Can you code it ?

Obviously there are many different options depending on design decisions, but here’s one:

```auto
@Injectable()
export class AppContext {
  ready: Promise<any>;
  private _isWebIntegration: boolean;

  constructor(private _storage: Storage) {
    this.ready = Promise.all([
      this._storage.get('isWebIntegration').then((wip) => this._isWebIntegration = wip),
      // &c &c for other similar stuff
    ]);
  }

  // don't call any of these until this.ready resolves

  isWebIntegration(): boolean {
    return this._isWebIntegration;
  }

  setWebIntegration(wip: boolean): Promise<any> {
    this._isWebIntegration = wip;
    return this._storage.set('isWebIntegration', wip);
  }
}

```

[Next page](https://forum.ionicframework.com/t/global-variables-on-ionic-2/45890.md?page=2)
