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

1
  • The example you have given is how you would define a "global" variable in typescript. What are you struggling with? Commented Feb 26, 2017 at 9:49

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.