Separate Development And Production URL In Angular 9

In this article, we will learn how to separate development and production URLs using the environment file in Angular.

During Angular application development, we use development APIs. Once development is done, we would like to use production APIs in our Angular application.

In the Angular CLI project, we get an environment folder with two files environment.ts and environment.prod.ts. Using these files developers can switch between development URLs and production URLs.

environment.ts

export const environment = {
  production: false,
  baseUrl: 'http://staging.thecodehubs.com/api/'
};

environment.ts file exports a constant JSON object environment. When you refer to environment object properties in your Angular application, all values shall be read from this file during development mode (i.e. ng serve or ng build).

 

environment.prod.ts

export const environment = {
  production: true,
  baseUrl: 'http://staging.thecodehubs.com/api/'
};

environment.prod.ts file exports the same JSON object and should have the same properties as of environment.ts file. When you build your application for production mode using ng build –prod, in that case, all values of environment.ts file shall get overridden by environment.prod.ts file.

 

Access environment Object

To access an environment object in whole Angular application.

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { environment } from 'environments/environment';

@Injectable({
  providedIn: 'root'
})
export class DataService {

  baseUrl = environment.baseUrl;

  constructor(private http: HttpClient) { }

  getData() {
    return this.http.get(this.baseUrl + '/GetData');
  }

}

 

Please give your valuable feedback and if you have any questions or issues about this article, please let me know.

Also, check How To Bind DropDownList With Validation In Angular

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories