繁体   English   中英

在 index.html 文件中使用环境变量

[英]Use environment variable in index.html file

我正在开发一个 Angular 应用程序,我使用外部 JavaScript 库:

 <-- the end of the body element -->
 <div id="webapps-sidepanel"></div>
 <script src="./assets/js/tecportalapps.js"></script>

 <script>
   $select('#webapps-sidepanel').getWebapps(localStorage.getItem('TMP_username'));
 </script>
</body>

一切正常,但现在本地存储变量名称已更改,我需要使用位于 environment.ts 文件中的环境名称:

export const environment = {
  production: true,
  *envName*: 'PROD',
};

所以我需要使用这样的东西:

 $select('#webapps-sidepanel').getWebapps(localStorage.getItem('TMP_*envName*'));

这可能吗? 欢迎任何关于我如何实现这一目标的想法。 也许我可以从 app.component.ts 调用 $select?

我认为你应该从 app.component.ts 添加你的脚本

export class AppComponent implements OnInit {

  constructor() {}

  ngOnInit() {
    this.loadScript();
  }

  public loadScript() {
    /* Create your script */
    const body = <HTMLDivElement> document.body;
    const script = document.createElement('script');
    script.src = './assets/js/tecportalapps.js';

    /* Do your stuff with environement variable or localstorage */
    console.log(environment.envName);
    console.log(localStorage.getItem("envName"));

    /* add your script to DOM */
    body.appendChild(script);
  }

}

在 index.html 中,您尚未脱离 Angular 的上下文,因此您没有机会读取环境文件的值。

尝试在 app.component.ts 中执行您的代码。

为此,您必须让 typescript 将 $select 识别为现有的 function。 有几种方法可以做到这一点(阅读更多: https://mariusschulz.com/blog/declaring-global-variables-in-typescript

例如, app.component.ts

(window as any).$select('#webapps-sidepanel').getWebapps(localStorage.getItem('TMP_' + environment.envName));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM