我正在使用angular,我想在index.html中使用环境变量进行Google Analytics(分析)。我这样尝试过:
<script>
import {environment} from "./environments/environment";
</script>
<!-- End Google Tag Manager (noscript) -->
<script async src="https://www.googletagmanager.com/gtag/js?id=" + environment.googleAnalytics></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', environment.googleAnalytics);
</script>
但不能在脚本链接中使用。你能帮我吗 ?在这个地方,https://www.googletagmanager.com/gtag/js?id=" + environment.googleAnalytics
在此串联中不起作用
答案 0 :(得分:0)
需要在您的依赖项中添加google anlytics,然后按照以下链接中的说明将跟踪代码添加到index.html。
npm install --save @types/google.analytics
此链接可能有助于找到解决方案。通过这个线程。
答案 1 :(得分:0)
您无法编写此类连接,因为<script>
是html标记,而不是JavaScript代码。也许您想通过javascript加载该脚本,以这种方式可以串联您的environment.googleAnalytics
属性。
答案 2 :(得分:0)
执行此操作的一个好方法是拥有不同的index.html
文件(index.dev.html
,index.prod.html
等),在其中您可以明确定义所需的环境变量。然后,使用文件替换功能,在它们之间进行切换(替换环境文件的方式相同)。
"fileReplacements": [
{
"replace": "src/index.html",
"with": "src/index.prod.html"
}
]
答案 3 :(得分:0)
您应该创建index.html的副本并将其命名为index.someenv.html。然后在您的angular.json环境配置中替换安装文件:
"fileReplacements": [{
"replace": "src/index.html",
"with": "src/index.someenv.html"
}]
在运行构建时,角度cli将替换这些文件