2

I am having tough time defining a global variable to be accessible in the whole app. The app is based on Ionic2 and Angular2.

I tried to many approaches but none worked. In some examples on SO I can't understand where to store the js file physically.

Exampe I tried: Example

Community
  • 1
  • 1
  • The example you have given is how you would define a "global" variable in typescript. What are you struggling with? – Oliver Cooke Feb 26 '17 at 09:49

1 Answers1

2

Create Globals class in app/globals.ts:

import { Injectable } from '@angular/core';

Injectable()
export class Globals{
    VAR1 = 'value1';
    VAR2 = 'value2';
}

In your component:

import { Globals } from './globals';

@Component({
    selector: 'my-app',
    providers: [ Globals ],
    template: `<h1>My Component {{globals.VAR1}}<h1/>`
})
export class AppComponent {
    constructor(private globals: Globals){
    }
}

You can use your globals in the html with {{globals.VARIABLENAME}}

Do not add class Globals as provider

Nico
  • 194
  • 1
  • 15
  • Note that this way it is possible to get multiple instances of the Globals class. Would be better to only declare the "Globals" once in app.module.ts providers – mwager Feb 27 '17 at 11:38