Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read values from environment variable Angular 4

Tags:

angular

I am trying to read the environment variable property using

process.env['KEY_TO_READ']

This KEY_TO_READ i am setting up in the environment variable. But, its not taking up at compile time only i am getting the below error:

Cannot find name 'process'.

Somewhere i read like in angular app we cannot use process because it will be defined at runtime. Is it correct ? If yes then can anyone suggest how i can achieve this . I don't want to use angular-cli environment file options.

like image 960
Rohitesh Avatar asked May 29 '18 05:05

Rohitesh


People also ask

Can Angular read environment variables?

Angular provides build-in support to configure and manage Environment Variables. It keeps the environment configuration under the folder src/environments folder.

What is .env file in Angular?

An Angular Application Environment is JSON configuration information that tells the build system which files to change when you use ng build and ng serve . Let's say you have a back end REST API deployed on a server that provides services to your Angular application.

What is environment TS in Angular?

A project's src/environments/ folder contains the base configuration file, environment.ts , which provides a default environment. You can add override defaults for additional environments, such as production and staging, in target-specific configuration files.


1 Answers

You ll have your environment file as,

environment.ts:

export const environment = {  
  production: false,
  envName: 'dev',
  KEY_TO_READ: 'test'
};

It is exported so you can import it:

import { environment } from './environment';

export class MyappAppComponent {  
  title = 'myapp works!';
  KEY_TO_READ = environment.KEY_TO_READ;
}
like image 145
Sravan Avatar answered Oct 24 '22 22:10

Sravan