如何在脚本标签中访问角度变量

时间:2018-08-13 18:24:40

标签: angular typescript

如何在脚本标签中访问角度变量跟踪ID(UA-123XXXXXX-1)

<app-root></app-root>
<script>
  (function(i, s, o, g, r, a, m) {
            i['GoogleAnalyticsObject'] = r;
            i[r] = i[r] || function() {
                (i[r].q = i[r].q || []).push(arguments)
            }, i[r].l = 1 * new Date();
            a = s.createElement(o),
                m = s.getElementsByTagName(o)[0];
            a.async = 1;
            a.src = g;
            m.parentNode.insertBefore(a, m);

        })(window, document, 'script', 'https://www.google-analytics.com/analytics.js', 'ga');

ga('create', 'UA-123XXXXXX-1', 'auto');// add your tracking ID here.
ga('send', 'pageview');


</script>

1 个答案:

答案 0 :(得分:3)

如果要从Angular进行操作,则需要从Angular进行整个操作。

// ga.ts
declare const ga: any;

export function startAnalytics(token) {
  (function(i, s, o, g, r, a, m) {
            i['GoogleAnalyticsObject'] = r;
            i[r] = i[r] || function() {
                (i[r].q = i[r].q || []).push(arguments)
            }, i[r].l = 1 * new Date();
            a = s.createElement(o),
                m = s.getElementsByTagName(o)[0];
            a.async = 1;
            a.src = g;
            m.parentNode.insertBefore(a, m);

        })(window, document, 'script', 'https://www.google-analytics.com/analytics.js', 'ga');

  ga('create', token, 'auto');
  ga('send', 'pageview');
}

// whatever.ts
import { startAnalytics } from './ga.ts';

// here e.g. retrieving your token from backend or whatsoever work
// you want to be done before

startAnalytics('whatever token you want');

实际上,我不确定ga('send', 'pageview');是您在SPA中想要的东西,但这不在您的问题范围内。