Angular 5 Constant

Angular Constant & Global Variables | Angular 9, 8, 7, 6, 5, 4, 2

How to CREATE constant in your Angular Apps? 

A constant is a value that can’t be changed by the program during normal execution.
                                                                 OR
Constants are of fixed values that do not change during the execution of a program. There are various types of constants. These can be :-
1.      Numeric
2.      Character
3.      Integer

4.      Other types

And constant class looks like

export class AppConstants {
    public static get baseURL(): string { return "http://localhost:4200/api"; }
}

And Use of constant in Services –

import { Injectable } from '@angular/core';
import {HttpClient, HttpParams, HttpHeaders} from "@angular/common/http";
import { Employee } from './employee';
import{ AppConstants} from '../app/constants'

@Injectable()
export class EmployeeService {
 
  //variable initialization
  headers : any;
  _baseURL : string;

  //constructor initialization
  constructor(private _htc:HttpClient) {
      this.headers = new HttpHeaders().set('content-type', 'application/json');
      this._baseURL = AppConstants.baseURL;
  }

  // POST employee - for creating a New employee.
  addEmployee(emp :any){
    var employee = {
        name:emp.name,
        Dep:emp.Dep,
        Des:emp.Des 
    } 
    return this._htc.post<Employee>(this._baseURL+'/Employees/Add', employee, (this.headers));
  }

  //DELETE employee - for delete employee.
  deleteEmployee(id :string){    
    return this._htc.delete<Employee>(this._baseURL+'/Employees/Delete/'+id);
  }
}

ANIL SINGH

Anil Singh is an author, tech blogger, and software programmer. Book writing, tech blogging is something do extra and Anil love doing it. For more detail, kindly refer to this link..

My Tech Blog - https://www.code-sample.com/
My Books - Book 1 and Book 2

www.code-sample.com/. Powered by Blogger.
^