首页 > 解决方案 > 报告数据未显示在嵌入式 API 中

问题描述

我设置了 OAuth 2.0 客户端 ID,从https://ga-dev-tools.appspot.com/embed-api/basic-dashboard/复制并粘贴代码以嵌入 Google Analytics API 的基本仪表板

但是,在我的本地主机服务器中,我看到“访问 Google Analytics”按钮,当单击并获得授权时,它只显示“您登录为:xxxxx@gmail.com”。不应该在文本下方显示图表和/或报告数据,就像在 Google Analytics 嵌入 API 概述文档中看到的那样?:

google默认嵌入api截图

这是我的实际内容:

文字下方缺少图表

这是完整的代码:

<!DOCTYPE html>
<html>
<head>
  <title>Embed API Demo</title>
</head>
<body>

<!-- Step 1: Create the containing elements. -->

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

<!-- Step 2: Load the library. -->

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


<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 code'
  });


  /**
   * 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>

</body>
</html>

我在这里想念什么?

标签: google-analytics-api

解决方案


viewSelector.execute()一旦身份验证成功,您需要调用。正如您现在所拥有的,它仅在第一次通过以下方式被调用:

代替

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

和:

// Render the view selector once user is authenticated.
gapi.analytics.auth.on('success', function(response) {
  viewSelector.execute();
});

推荐阅读