I would like some variables to be accessible everywhere in an Angular 2
in the Typescript
language. How should I go about accomplishing this?
This question is related to
typescript
angular
That's the way I use it:
global.ts
export var server: string = 'http://localhost:4200/';
export var var2: number = 2;
export var var3: string = 'var3';
to use it just import like that:
import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Rx';
import * as glob from '../shared/global'; //<== HERE
@Injectable()
export class AuthService {
private AuhtorizationServer = glob.server
}
EDITED: Droped "_" prefixed as recommended.
I like the answer of @supercobra, but I would use the const keyword as it is in ES6 already available:
//
// ===== File globals.ts
//
'use strict';
export const sep='/';
export const version: string="22.2.2";
I don't know the best way, but the easiest way if you want to define a global variable inside of a component is to use window
variable to write like this:
window.GlobalVariable = "what ever!"
you don't need to pass it to bootstrap or import it other places, and it is globally accessibly to all JS (not only angular 2 components).
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){
}
}
Note: You can add Globals service provider directly to the module instead of the component, and you will not need to add as a provider to every component in that module.
@NgModule({
imports: [...],
declarations: [...],
providers: [ Globals ],
bootstrap: [ AppComponent ]
})
export class AppModule {
}
IMHO for Angular2 (v2.2.3) the best way is to add services that contain the global variable and inject them into components without the providers
tag inside the @Component
annotation. By this way you are able to share information between components.
A sample service that owns a global variable:
import { Injectable } from '@angular/core'
@Injectable()
export class SomeSharedService {
public globalVar = '';
}
A sample component that updates the value of your global variable:
import { SomeSharedService } from '../services/index';
@Component({
templateUrl: '...'
})
export class UpdatingComponent {
constructor(private someSharedService: SomeSharedService) { }
updateValue() {
this.someSharedService.globalVar = 'updated value';
}
}
A sample component that reads the value of your global variable:
import { SomeSharedService } from '../services/index';
@Component({
templateUrl: '...'
})
export class ReadingComponent {
constructor(private someSharedService: SomeSharedService) { }
readValue() {
let valueReadOut = this.someSharedService.globalVar;
// do something with the value read out
}
}
Note that
providers: [ SomeSharedService ]
should not be added to your@Component
annotation. By not adding this line injection will always give you the same instance ofSomeSharedService
. If you add the line a freshly created instance is injected.
I like the solution from @supercobra too. I just would like to improve it slightly. If you export an object which contains all the constants, you could simply use es6 import the module without using require.
I also used Object.freeze to make the properties become true constants. If you are interested in the topic, you could read this post.
// global.ts
export const GlobalVariable = Object.freeze({
BASE_API_URL: 'http://example.com/',
//... more of your variables
});
Refer the module using import.
//anotherfile.ts that refers to global constants
import { GlobalVariable } from './path/global';
export class HeroService {
private baseApiUrl = GlobalVariable.BASE_API_URL;
//... more code
}
A shared service is the best approach
export class SharedService {
globalVar:string;
}
But you need to be very careful when registering it to be able to share a single instance for whole your application. You need to define it when registering your application:
bootstrap(AppComponent, [SharedService]);
But not to define it again within the providers
attributes of your components:
@Component({
(...)
providers: [ SharedService ], // No
(...)
})
Otherwise a new instance of your service will be created for the component and its sub-components.
You can have a look at this question regarding how dependency injection and hierarchical injectors work in Angular 2:
You should notice that you can also define Observable
properties in the service to notify parts of your application when your global properties change:
export class SharedService {
globalVar:string;
globalVarUpdate:Observable<string>;
globalVarObserver:Observer;
constructor() {
this.globalVarUpdate = Observable.create((observer:Observer) => {
this.globalVarObserver = observer;
});
}
updateGlobalVar(newValue:string) {
this.globalVar = newValue;
this.globalVarObserver.next(this.globalVar);
}
}
See this question for more details:
I think the best way is to share an object with global variables throughout your application by exporting and importing it where you want.
First create a new .ts file for example globals.ts and declare an object. I gave it an Object type but you also could use an any type or {}
export let globalVariables: Object = {
version: '1.3.3.7',
author: '0x1ad2',
everything: 42
};
After that import it
import {globalVariables} from "path/to/your/globals.ts"
And use it
console.log(globalVariables);
See for example Angular 2 - Implementation of shared services
@Injectable()
export class MyGlobals {
readonly myConfigValue:string = 'abc';
}
@NgModule({
providers: [MyGlobals],
...
})
class MyComponent {
constructor(private myGlobals:MyGlobals) {
console.log(myGlobals.myConfigValue);
}
}
or provide individual values
@NgModule({
providers: [{provide: 'myConfigValue', useValue: 'abc'}],
...
})
class MyComponent {
constructor(@Inject('myConfigValue') private myConfigValue:string) {
console.log(myConfigValue);
}
}
Source: Stackoverflow.com