Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change variable value in index.html based on the environment in angular

How can i change config.apiKey value based on the angular environments like Development & Production.

For Production config.appKey = 'AB-AAB-AAB-MPR';

For Development config.appKey = 'AC-DDR-SST-DKR';

Please find the code for reference.

`<script charset='UTF-8'>
    window['adrum-start-time'] = new Date().getTime();
    (function(config){
        config.appKey = 'AC-DDR-SST-DKR';
    })(window['adrum-config'] || (window['adrum-config'] = {}));
  </script>
`

Thanks
like image 270
Bikshu s Avatar asked Feb 06 '20 06:02

Bikshu s


2 Answers

Reading environment file in index.html will be difficult. I am not saying it is not possible there may be a workaround for that. But I recommend you to do this in app.component.ts file on

ngOnInit() {
    this.loadScript();
}

private loadScript() {
    const script = document.createElement('script');
    script.type = 'text/javascript';
    script.innerHTML = 'window["adrum-start-time"] = new Date().getTime(); (function(config){ config.appKey = ' + environment.key + '; })(window["adrum-config"] || (window["adrum-config"] = {}));';
    const head = document.getElementsByTagName('head')[0];
    if (head !== null && head !== undefined) {
      document.head.appendChild(script);
    }
}

Hopefully, this will solve the problem

like image 61
Abdul Jabbar Avatar answered Oct 04 '22 00:10

Abdul Jabbar


You can use your angular.json to replace your index.html file. just create a copy of the index.html and name it to index.env.html and then in your angular.json you can use fileReplacements in your specific env like the following

"fileReplacements": [
    {
        "replace": "src/index.html",
        "with": "src/index.env.html"
    }
]
like image 37
Jazib Avatar answered Oct 04 '22 01:10

Jazib