All variables which vary based on the environment, should be placed inside these two files appropriately. Check the examples given below for the API Endpoint.
// environment.ts environment variables
export const environment = {
production: false,
BackendAPIEndpoint: "https://dev.endpoint.com"
};
// environment.prod.ts environment variables
export const environment = {
production: true,
BackendAPIEndpoint: "https://prod.endpoint.com"
};
To access the variables, import the environment constant, and then use it as follows:
import { environment } from '../environments/environment'; //change path accordingly
Usage:
const BackendAPIEndpoint = environment.BackendAPIEndpoint;
Dealing with 1 or More Environment:
// environment.staging.ts environment variables
export const environment = {
production: true
BackendAPIEndpoint: "https://staging.endpoint.com"
};
Next, we need to make configuration changes to our angular.json – at the root of our workspace. This will enable Angular CLI to recognize our two new environments and use the new environment files we created in the previous step.
"configurations": {
"production": {
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.prod.ts"
}
],
"optimization": true,
"outputHashing": "all",
"sourceMap": false,
"extractCss": true,
"namedChunks": false,
"aot": true,
"extractLicenses": true,
"vendorChunk": false,
"buildOptimizer": true,
"serviceWorker": true
}
}
Your new configuration for staging environment should look like this:
"configurations": {
"production": {
...
},
"staging": {
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.staging.ts"
}],
"optimization": true,
"outputHashing": "all",
"sourceMap": true,
"extractCss": false,
"namedChunks": false,
"aot": false,
"extractLicenses": true,
"vendorChunk": false,
"buildOptimizer": true,
"serviceWorker": true
}
}
Building your App
Finally, to build your application with the new custom environment, use the –configurations=environment-name flag, as show below:
//for development environment
ng build
//for staging environment
ng build --prod
//for staging environment
ng build --configuration=staging
And that’s it, you can now configure your Angular Application.
Thanks