Angular – Environment Variables

By | 10/07/2020

In this post, we will see how to use environment variables in Angular.

We will use the same Angular project created for the post How to Dockerize an Angular application and we will add a call at the Web API Service that I have deployed on Docker.hub:

First of all, we run the Docker image using the command
docker run -p 80:80 commander2020/webapidocker

and, if we go to http://localhost/users, this will be the result:

Now, we will modify the angular project, in order to use the Web API.
First of all, we create a class called userwebapi, where we will define the same object used by Web API as output:
ng g class entities/userwebapi

[USERWEBAPI.TS]

export class Userwebapi {
    id: number;
    userName: string;
    password: string;
    createdAt: string;

    constructor(inputId: number, inputUserName: string, inputPassword: string, inputCreatedAt: string) 
    {
        this.id = inputId;
        this.userName = inputUserName;
        this.password = inputPassword;
        this.createdAt = inputCreatedAt;
    }
}



Then, we create a service called Dockerservice, where we will call the Web API:
ng g service services/dockerservice

[DOCKERSERVICE.SERVICE.TS]

import { Injectable } from '@angular/core';
import { Userwebapi } from '../entities/userwebapi';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';
import { environment } from '../../environments/environment';

@Injectable({
  providedIn: 'root'
})
export class DockerserviceService 
{
  // definition of the Web API's url, using the variable environment.urlwebapi
  urlWebAPI: string = environment.urlwebapi;

  constructor(private http: HttpClient) { 
  }

  GetListUsers(): Observable<Array<Userwebapi>>{
      return this.http.get<Array<Userwebapi>>(this.urlWebAPI);
  }
}



Finally, we create a component called listwebapi, that we will use to show the list of users:
ng g c pages/listwebapi

[LISTWEBAPI.COMPONENT.TS]

import { Injectable } from '@angular/core';
import { Userwebapi } from '../entities/userwebapi';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';
import { environment } from '../../environments/environment';

@Injectable({
  providedIn: 'root'
})
export class DockerserviceService 
{
  // definition of web api url, using the variable environment.urlwebapi
  urlWebAPI: string = environment.urlwebapi;

  constructor(private http: HttpClient) { 
  }

  GetListUsers(): Observable<Array<Userwebapi>>{
      return this.http.get<Array<Userwebapi>>(this.urlWebAPI);
  }
}



Now, in order to use the new component, we have to modify:

[MENU.COMPONENT.HTML]

<nav class="navbar navbar-dark bg-dark mb-5">
  <a class="navbar-brand" routerLink="homepage">HOMEPAGE</a>
  <div class="navbar-expand mr-auto">
    <ul class="nav navbar-nav" routerLinkActive="active">
        <li class="nav-item"><a class="nav-link" routerLink="/list">[Page List]</a></li>
        <li class="nav-item"><a class="nav-link" routerLink="/listwebapi">[Page List By Web API]</a></li>
    </ul>
  </div>
</nav>



[APP-ROUTING.MODULE.TS]

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { PagelistComponent } from './pages/pagelist/pagelist.component';
import { HomepageComponent } from './share/homepage/homepage.component';
import { ListwebapiComponent } from './pages/listwebapi/listwebapi.component';

const routes: Routes = [
  { path: '', pathMatch: 'full', redirectTo: 'homepage'},
  { path: 'homepage', component: HomepageComponent },
  { path: 'list', component: PagelistComponent },
  { path: 'listwebapi', component: ListwebapiComponent },
  { path: '**', pathMatch: 'full', redirectTo: 'homepage' }  
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }



And finally, we have to define the variable environment called environment.urlwebapi, used into listwebapi.component.ts for the Web API’s url.

[ENVIRONMENTS/ENVIRONMENT.PROD.TS]

export const environment = {
  production: true,
  urlwebapi: "https://webapidocker.azurewebsites.net/users"
};



[ENVIRONMENTS/ENVIRONMENT.TS]

export const environment = {
  production: false,
  urlwebapi: "http://localhost/users"
};



In this way, when we run the application in Dev mode, it will use the Web API in localhost, instead in Prod mode, it will use the Web API deployed in Azure.

We start to run the application in Dev mode, using the command
ng serve:



In order to verify that it works fine, we open a browser and we go to http://localhost:4200

Now, if we stop the docker container runs on our machine, the application will no longer work:

But, if we run the application in Prod mode, it will work again because, in Prod mode it uses the Web API deployed on Azure:

For running the application in Prod mode, we have to use the command:
ng serve –prod

Now, if we go to http://localhost:4200, this will be the result:

By design in an Angular project there are only Prod and Dev as Environments but, it is quite easy to add other custom environment.
For all information we can see the official Angular Web site.



Leave a Reply

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