Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use default values for Angular environments

I have several environment files for my Angular application :

  • environment.ts
  • environment.dev.ts
  • environment.prod.ts

I'd like to use default variables shared by all environments without duplicating them in every file. If I add a variable 'homeUrl' only in environment.ts for example :

export const environment = {
  production: false,
  apiUrl: 'http://some-backend-url/',
  homeUrl: '/illustrator/directory'
};

When I run the application with the dev configuration, my variables from environment.dev.ts are loaded properly but homeUrl is undefined as it's only declared in environment.ts file.

Is there a way to use default variables shared between environments without copying them ?

like image 787
bobuns Avatar asked Feb 20 '19 16:02

bobuns


People also ask

Can Angular access environment variables?

Introduction. If you're building an app that uses an API, you'll want to use your API key for testing environments during development and your API key for live environments during production. In Angular, you can create environment variables with the environment.

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. For example: myProject/src/environments.


Video Answer


2 Answers

You can import default variables from outside.

default.ts:

export const default = {
  apiUrl: 'http://some-backend-url/',
  homeUrl: '/illustrator/directory'
}

in environment.ts:

import {default} from 'default'

export const environment = {
  ...default,
  production: false
}

and import it in all files. So in this way you can modify only in default.ts file and will be apply automaticaly in all enviroments

like image 105
Oleg Avatar answered Oct 13 '22 11:10

Oleg


My answer will improve Oleg answer:

1. Base interface:

// config.ts
export interface Config {
   production: boolean;
   apiUrl: string;
   homeUrl: string;
   // added other need config definition.
}

2. Base environment:

// environment.base.ts
export const environmentBase = {
  apiUrl: 'http://some-backend-url/',
  homeUrl: '/illustrator/directory'
  // add more base, default, share config definitions.
}

3. Production environment:

// environment.prod.ts
export const environment: Config = {
    ...environmentBase,
  production: true,
}

4. Development environment:

// environment.dev.ts
export const environment: Config = {
    ...environmentBase,
  production: false,
}
like image 38
Khaled Lela Avatar answered Oct 13 '22 11:10

Khaled Lela