HiveBrain v1.2.0
Get Started
← Back to all entries
snippettypescriptangularCritical

How can I declare a global variable in Angular 2 and up / Typescript?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
angulartypescripthowglobalanddeclarevariablecan

Problem

I would like some variables to be accessible everywhere in an Angular 2 in the Typescript language. How should I go about accomplishing this?

Solution

Here is the simplest solution without Service or Observer:

Put the global variables in a file and export them.

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

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


To use globals in another file, use an import statement:
import * as myGlobals from 'globals';

Example:

// 
// ===== 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 * as myGlobals from 'globals'; //<==== this one (**Updated**)
 
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";

         ...

        }
    }

Code Snippets

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

export const sep='/';
export const version: string="22.2.2";
// 
// ===== 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 * as myGlobals from 'globals'; //<==== this one (**Updated**)
 
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";

         ...

        }
    }

Context

Stack Overflow Q#36158848, score: 225

Revisions (0)

No revisions yet.