我有一些Angular项目之外的Google Analytics代码。如果环境是生产环境,我只想将其包括在内。
我知道Angular项目中有一个环境变量,你可以在typescript中引用它。。。
if (environment.production) {
// do stuff
}
不过,如果在Angular之外有一些静态代码,那也无济于事。我试着把谷歌分析代码放在Angular中,但似乎有问题,因为找不到范围,打字脚本也不喜欢
现在,我的最佳解决方案是手动检查主机名,这可能不是最佳解决方案(这在angular应用程序外的index.html中(。。。
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-00000000-0"></script>
<script>
if(location.hostname === "productionurl.com") {
// insert google analytics tracking code
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'UA-000000000-0');
}
</script>
我习惯于使用web.config文件,这会很简单,但这个项目使用角度配置来处理环境变量。
也许有一种方法可以从香草javascript中的"getAllAngularRootElements(("获得环境,但我还没有找到方法。
对我来说,目前最干净的解决方案是使用第二个index.html
文件,例如index.prod.html
,并在构建过程中使用angular.json
中"production"
env配置中的"fileReplacements"
属性来替换原始文件。
查看此处:https://github.com/angular/angular-cli/wiki/stories-application-environments
角度8+的UDPATE
在构建时,"fileReplacements"
不适用于替换index.html
-使用"index"
:
"index": {
"input": "src/index.prod.html",
"output": "index.html"
},
更多信息请点击此处:https://github.com/angular/angular-cli/issues/14599
您是否尝试通过Angulartics设置Google Analytics(https://github.com/angulartics/angulartics)?我认为这应该能解决你的问题。