To define constants which are globally available in your Angular app, here is my suggested way to do so.
Create a TypeScript file to declare Global Constants
Create a TypeScript
file and name it e.g. globals.ts
. Inside the file, create const
and assign value to each const
.
With const
, it prevents re-assignment to a variable.
app/_shared/global.ts
'use strict';
export const API_ENDPOINT: string ='http://127.0.0.1:6666/api/';
export const VERSION: string ="22.2.2";
export const PAGE_SIZE: number = 10;
To Consume Global Constants’ Values
To use globals in another file use an import statement: import * as Globals from ‘./globals’;
app/app.component.ts
import {Component, OnInit} from '@angular/core';
import * as Globals from './_shared/globals'; //<==== this one
@Component({
selector: 'cloudberry-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
// Here we access the global var reference.
//
public versionNumber: string ="Version number: " + Globals.VERSION;
...
}
Reference:
https://www.typescriptlang.org/docs/handbook/variable-declarations.html