Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 - angular-cli: set global variable on build

This is my first time trying to deploy an Angular2 application. I want to set the URL of an API endpoint, and I would like for it to be different in every environment.

Is there a way to make ng build or any other tools that would allow set this for me prior to deployment?

like image 917
blgrnboy Avatar asked Nov 18 '16 18:11

blgrnboy


1 Answers

With the Angular CLI tool you can configure different environments.

ng build can specify both a build target (--target=production or --target=development) and an environment file to be used with that build (--environment=dev or --environment=prod). By default, the development build target and environment are used.

The mapping used to determine which environment file is used can be found in angular-cli.json:

"apps": {
  "environmentSource": "environments/environment.ts",
  "environments": {
    "dev": "environments/environment.ts",
    "prod": "environments/environment.prod.ts"
  }
}

These options also apply to the serve command. If you do not pass a value for environment, it will default to dev for development and prod for production.

You can also add your own env files other than dev and prod.

Then, in your code, you can do a simple check, just like the default one in the main.ts file:

if (environment.production) {
  enableProdMode();
}

Check out the build targets and environment files section in their docs for more details.

PS: Here's a similar question, you might find the answers there useful too.

like image 83
Kaloyan Kosev Avatar answered Sep 16 '22 15:09

Kaloyan Kosev