Angular 10 Define global constants Example
In this tutorial, we will explain to you how to define global constants in angular 10. constants mean one time declares variables that don’t change every time value.
We will give you a simple example of how to define a global constant in our angular application. when we are calling rest API at that time we use the API path. if you don’t want to repeat the API path every time then you can define the global.
Create the Constant File
first, we need to create the constant class file, after then we will define the constant in this file. for that, you can see the below example.
src/app/common/appSettings.ts
1 2 3 | export class AppSettings { public static apiURL='http://127.0.0.1:8000/api/'; } |
Import the Constant Class in the Component
now, we need to import the appSettings constant class into the app.component.ts component file. so we will import that file and check that constant value.
src/app/app.component.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | import { Component, OnInit } from '@angular/core'; import{ appSettings } from './common/appSettings'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit{ constructor() { } ngOnInit() { console.log(appSettings.apiURL); } } |
Run Our Angular Application
Now we will run our Angular application using the below command.
1 | ng serve |
Output
1 | http://127.0.0.1:8000/api/ |