Environments

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:

  1. Add the base address in the default environment configuration with the following steps:
    1. Open the environment.ts file in the src/environments folder.
    2. Add the base address configuration as follows:
export const environment = {
production: false,
marketApiBaseUri: 'http://localhost:55564/api/',
};
  1. Add the base address in the production environment configuration:
    1. Open the environment.prod.ts file.
    2. 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/',
};
  1. 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[]);
}
}
  1. 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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.135.206.254