supercobra supercobra - 1 year ago 425
TypeScript Question

What is the best way to declare a global variable in Angular 2 / Typescript

I would like some variables to be accessible everywhere in an

Angular 2
in the
language?. What is the best best to do this?

Answer Source

Here is the simplest solution w/o Service nor Observer:

Put the global variables in a file an export them.

// ===== File globals.ts    
'use strict';

export var sep='/';
export var version: string="22.2.2";    

To use globals in another file use an import statement: import myGlobals = require('./globals');


// ===== File heroes.component.ts    
import {Component, OnInit} from 'angular2/core';
import {Router} from 'angular2/router';
import {HeroService} from './hero.service';
import {HeroDetailComponent} from './hero-detail.component';
import {Hero} from './hero';
import myGlobals = require('./globals'); //<==== this one

export class HeroesComponent implements OnInit {
    public heroes: Hero[];
    public selectedHero: Hero;
    // Here we access the global var reference.
    public helloString: string="hello " + myGlobals.sep + " there";



Thanks @eric-martinez

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download