In this tutorial, we will explain to you how to define global constants in angular 10(Angular 10 Define global constants Example). 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.
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
export class AppSettings {
public static apiURL='http://127.0.0.1:8000/api/';
}
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
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);
}
}
Now we will run our Angular application using the below command.
ng serve
Output
http://127.0.0.1:8000/api/