Using environment-specific variables in Angular the right way.
Environment-specific variables are useful when a project has multiple build configurations, such as production and staging, and each environment needs a different API base URL.
Suppose your project has two environments:
- Production
- Staging
and each one has a different API base URL.
Setup
Angular 15 and later do not create environment files automatically, so generate them with:
ng generate environments
That creates two files:
src/environments/environment.tssrc/environments/environment.development.ts
Then create environment.staging.ts by copying environment.ts and updating the values.
src/
app/
app.component.html
app.component.ts
environments/
environment.development.ts
environment.staging.ts
environment.ts
services/
api.service.ts
api.service.spec.ts
Now add the API URLs to your environment files.
environment.ts
export const environment = {
production: true,
apiUrl: 'https://my-prod-api-url',
};
environment.development.ts
export const environment = {
production: false,
apiUrl: 'http://my-local-api-url',
};
environment.staging.ts
export const environment = {
production: false,
apiUrl: 'https://my-staging-api-url',
};
Configuration for different environments
The ng generate environments command automatically adds the development configuration to angular.json:
"configurations": {
"development": {
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.development.ts"
}
]
}
}
Add the staging configuration manually:
"configurations": {
"staging": {
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.staging.ts"
}
]
}
}
Using a production-like configuration for staging is usually a sensible default.
Using the environment variable in code
Use environment.apiUrl from your service:
import { Injectable } from '@angular/core';
import { environment } from '../environments/environment';
@Injectable({
providedIn: 'root',
})
export class ProductService {
apiUrl = environment.apiUrl;
getProducts(): Observable<Products> {
const url = this.apiUrl + '/api/products';
return this.http.get<Products>(url);
}
}
Now you are ready to build for different environments:
ng build
ng build --configuration=staging
Happy coding.