Google Analytics 嵌入 api 不适用于 Angular 2 应用程序

2024-05-27

我使用以下代码将 Google Analytics api 嵌入到我的 Angular 2 应用程序中:

我的组件.html

  <div id="embed-api-auth-container"></div>
  <div id="chart-container"></div>
  <div id="view-selector-container"></div>

<script>

  gapi.analytics.ready(function() {

    /**
     * Authorize the user immediately if the user has already granted access.
     * If no access has been created, render an authorize button inside the
     * element with the ID "embed-api-auth-container".
     */
    gapi.analytics.auth.authorize({
      container: 'embed-api-auth-container',
      clientid: My-Client-Id
    });


    /**
     * Create a new ViewSelector instance to be rendered inside of an
     * element with the id "view-selector-container".
     */
    var viewSelector = new gapi.analytics.ViewSelector({
      container: 'view-selector-container'
    });

    // Render the view selector to the page.
    viewSelector.execute();


    /**
     * Create a new DataChart instance with the given query parameters
     * and Google chart options. It will be rendered inside an element
     * with the id "chart-container".
     */
    var dataChart = new gapi.analytics.googleCharts.DataChart({
      query: {
        metrics: 'ga:sessions',
        dimensions: 'ga:date',
        'start-date': '30daysAgo',
        'end-date': 'yesterday'
      },
      chart: {
        container: 'chart-container',
        type: 'LINE',
        options: {
          width: '100%'
        }
      }
    });


    /**
     * Render the dataChart on the page whenever a new view is selected.
     */
    viewSelector.on('change', function(ids) {
      dataChart.set({query: {ids: ids}}).execute();
    });

  });
</script>

将 My-Client-Id 替换为 Google 客户端 ID,并在 index.html 标记中添加加载 platform.js 代码,如下所示:

     <script>
    (function(w,d,s,g,js,fs){
      g=w.gapi||(w.gapi={});g.analytics={q:[],ready:function(f){this.q.push(f);}};
      js=d.createElement(s);fs=d.getElementsByTagName(s)[0];
      js.src='https://apis.google.com/js/platform.js';
      fs.parentNode.insertBefore(js,fs);js.onload=function(){g.load('analytics');};
    }(window,document,'script'));
  </script>

我已经在基于 jQuery 的应用程序中测试了相同的代码,该代码工作正常,但在 Angular2 应用程序中显示空白页面,没有 JavaScript 控制台错误。

我也已将该网站添加到授权的 JavaScript 来源。我们还需要为 Angular2 应用程序做任何其他配置吗?

供您参考,我已经创建了 oAuth 客户端 ID,启用了 Analytics API,将网站添加到授权的 JavaScript 源并禁用了我的广告拦截器。


组件 HTML 文件中的 script 标签是按角度自动剥离 http://blog.davidjs.com/2018/09/insert-script-tags-in-angular-components/

因此,您需要将gapi.analytics.ready函数移至Mycomponent.ts文件中的ngOnInit()函数中。

index.html 文件中的 script 标记很好,您可以保留它。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Google Analytics 嵌入 api 不适用于 Angular 2 应用程序 的相关文章

随机推荐