Reputation: 3025
We have an Angular app which is hosted using Asp.Net Core on Azure. The app requires several URIs that are dependent on the environment (deployment slot) in which it is running.
Azure provides a great mechanism for injecting environment variables for server side code where settings can be specified per deployment slot. We need to be able to configure the Angular app at run time using this configuration specified in Azure.
What is the best mechanism to forward Azure application configuration on to the Angular client app so they are detected when the Angular app bootstraps?
A quick and dirty approach is to specify the environment name variable in Azure then set some global variables in Index.htm using the Asp.Net Core Environment Tag helpers:
<environment names="azure-development">
<script type="text/javascript">
(function (window) {
window.__env = window.__env || {};
window.__env.environmentName = 'azure-development';
window.__env.apiUri = 'DevApiUriAddress';
}(this));
</script>
</environment>
<environment names="azure-test">
<script type="text/javascript">
(function (window) {
window.__env = window.__env || {};
window.__env.environmentName = 'azure-test';
window.__env.apiUri = 'TestApiUriAddress';
}(this));
</script>
</environment>
...and register some kind of injectable class Angular provider to access these:
import { Injectable } from '@angular/core';
function _window(): any {
// return the global native browser window object
return window;
}
@Injectable()
export class EnvConfig{
get environmentName(): string {
return _window().__env.environmentName;
}
}
However this feels like a big hack.
What better alternatives are there?
Upvotes: 0
Views: 2300
Reputation: 4862
You can just access the environment variables directly from Node, using
process.env.ENV_VAR_NAME
To do this needs two steps:
Create your environment variables (called App Settings, in Azure) You'll find these in the portal under your web app's menu "Application Settings" -> "App settings"
Those settings are now available globally in your TypeScript code (or JS - whatever you happen to be running), and you can access them easily by name as in the following example:
Assuming I have set up an environment variable called "SuperSecretPassword", the I can access it ANYWHERE like this
const password: string = process.env.SuperSecretPassword;
And thats all there is to it :)
Upvotes: 2