Tag Archives: global variables

Global variables in Ionic 2

[Updated for the latest version of Ionic 2]

I’ve seen a couple of questions in forums recently relating to global variables in Ionic 2 applications and what the “best practice” is.  In my Ionic 2 apps I like to handle global variables by injecting some sort of shared-data service into any components that need it.

import {Injectable} from 'angular/core';

@Injectable()
export class GlobalVars {
  
  constructor() {
    this.myGlobalVar = "";
  }

  setMyGlobalVar(value) {
    this.myGlobalVar = value;
  }

  getMyGlobalVar() {
    return this.myGlobalVar;
  }

}

in app.module.ts I would then import the service:

import {GlobalVars} from ./providers/globalVars;

and specify it as a provider:

providers: [GlobalVars]

and then it can be injected and used in any component.  To see this in action, take a look at the Conference app that the Ionic team are building as a reference project for Ionic 2.  Take a look at the user-data provider and see how they use that across the application to maintain data (such as the favourites list).



I’m a mobile applications developer based in the UK, concentrating primarily on hybrid application development with Ionic and Ionic 2 but also with native development skills. Please visit www.crossplatformsolutions.co.uk for more information about me and how I may be able to help you with mobile application development, particularly with Ionic 2 but also with other mobile frameworks and technologies.  Thanks for visiting.