Typically, apps require environment-specific configuration. In this specific app, we have the base address of the RESTful API that should change across environments.
Angular provides a basic solution for configuration through its environments feature. Let's use environment configuration with the RESTful API base address, as follows:
- Add the base address in the default environment configuration with the following steps:
- Open the environment.ts file in the src/environments folder.
- Add the base address configuration as follows:
export const environment = {
production: false,
marketApiBaseUri: 'http://localhost:55564/api/',
};
- Add the base address in the production environment configuration:
- Open the environment.prod.ts file.
- Add the base address configuration. Currently, the code uses the same address—this should be changed later when the address of the API in the deployed environment is known:
export const environment = {
production: false,
marketApiBaseUri: 'http://localhost:55564/api/',
};
- Use the configured marketApiBaseUri in CategoriesService as follows, replacing the previous hardcoded value, and therefore supporting different environments:
...
import { environment } from '../../../../environments/environment';
...
export class CategoriesService {
private readonly apiUri = environment.marketApiBaseUri;
constructor(private readonly http: HttpClient) {}
loadCategories(): Promise<Category[]> {
return this.http
.get(`${this.apiUri}products/categories`)
.toPromise()
.then(result => result as Category[]);
}
}
- Use the configured marketApiBaseUri in ProductsService as follows, replacing the previous hardcoded value, and therefore supporting different environments:
…
import { environment } from '../../../../environments/environment';
…
export class ProductsService {
private readonly apiUri = environment.marketApiBaseUri;
constructor(private readonly http: HttpClient) { }
loadProducts(categoryName: string): Promise<Product[]> {
return this.http
.get(`${this.apiUri}products/searchcategory/${categoryName}`)
.toPromise()
.then(result => result as Product[]);
}
}
Congratulations! You can now set different configurations for production when you deploy the application in a later chapter by using the following command:
ng build --prod
You can find all the client-side related code in a public GitHub repository at https://github.com/azuker/frontend-web-dev.