【问题标题】:Use environment variable in index.html file在 index.html 文件中使用环境变量
【发布时间】:2020-07-20 10:53:15
【问题描述】:

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

 <-- 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?

【问题讨论】:

  • 你的意思是像localStorage.getItem('TMP_' + environment.envName)
  • @Lain,是的,但是如果我想这样使用它,我会收到此错误:未捕获的 ReferenceError:未定义环境
  • 好吧,如果你想使用它,你必须在某处/以某种方式定义/包含它

标签: javascript angular typescript angular8


【解决方案1】:

我认为你应该从 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
【解决方案2】:

在 index.html 中你已经脱离了 Angular 的上下文,所以你没有机会读取你的环境文件的值。

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

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

例如,app.component.ts:

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

【讨论】:

    猜你喜欢
    • 2020-03-02
    • 2021-10-07
    • 2019-01-15
    • 2022-10-17
    • 2020-01-17
    • 1970-01-01
    • 1970-01-01
    • 2021-04-15
    • 2017-07-29
    相关资源
    最近更新 更多