Angular CLI: Change REST API URL on build

Dont hard code the URL.
Use environment.prod.ts and environment.ts files which are inside src/environments.
for localhost, in environment.ts file use some variable to save your url.

export const environment = 
{
    production: false,
    API_URL: 'http://localhost:8080',
};

for production, in environment.prod.ts

export const environment = 
{
    production: true,
    API_URL: 'http://api.productionurl.com',
};

When using in your code import the variable,

import { environment } from '../../environments/environment';
....
....

private API_URL= environment.API_URL;

whenever your are using for production use angular cli command option

ng build --env=prod

The file contents for the current environment will overwrite these during build.
The build system defaults to the dev environment which uses environment.ts, but if you do
ng build --env=prod then environment.prod.ts will be used instead.
The list of which env maps to which file can be found in .angular-cli.json.

For more queries refer,
https://angular.io/guide/deployment

Leave a Comment

error code: 521