Reputation: 373
Recently we came across this situation when we want to deploy same angular build (dist) using jenkins to multiple environments which implies different backend url.
'ng build --configuration $ENV' (angular-6) with backend url mentioned in 'src/environment/environment.$ENV.ts'
was clearly not a solution for us because that would mean creating multiple build specific to environments.Upvotes: 7
Views: 4430
Reputation: 4841
Step - 1 : Create a js file
Just add a js file inside the assets directory
Let say the name is config.js and put all configurations inside that Eg :
var myAppGlobalConfig = { param1: 'value1' };
var BASE_URL = "http://xxx.backend.xxx/api/";
var GET_DATA = BASE_URL + "data.go";
Step - 2 : Include in index.html
Now in the index.html just include that script before any other script
<script src="assets/config.js"></script>
Step - 3: Use them inside your typescript classes
For example, you can assign http endpoint addresses.
this.http.get(window["DATA_URL"]).subscribe(...)
Further, in different environments just change global variables declared in the config.js
Upvotes: 1
Reputation: 373
This is how we solved it: (Reference: https://github.com/angular/angular-cli/issues/4318, Special thanks to: Michaël Arnauts)
Create a js file in dist/assets folder and define a global js variable there:
dist/assets/env.js
window._env = {
backendUrl: 'https://localhost:XXXX/',
};
Point to this global js variable in your environment.$ENV.ts file:
src/environments/environment.$ENV.ts
export const environment = {
production: true,
backendUrl: (<any>window)._env.backendUrl,
};
Add reference of js in your index.html
...
<head>
...
<script src="/assets/env.js"></script>
</head>
...
Create your environment value js files:
src/environments/environment.$ENV.values.js
window._env = {
backendUrl: 'https://dev.example.com:XXXX/',
};
Create build (dist)
Finally, at the time of deployment do:
cp src/environments/environment.$ENV.values.js dist/assets/env.js
Done!
Please note, step #1 is required so that you wouldn't require to do #6 on local.
Upvotes: 8