簡體   English   中英

將Google Analytics(分析)值轉換為變量

[英]Cast Google Analytics Value to variable

我正在使用GoogleAnalytics Embed API來創建自定義分析儀表板。

目前,我的代碼如下所示:

我的問題是我試圖在其他計算中使用變量CurrentUsers

這是我的代碼

var CurrentUsers; // declared globally

gapi.analytics.ready(function() {
    var CurrentVisitorsData = new gapi.analytics.report.Data({
        query: {
            ids: 'ga:xxxxxx',
            metrics: 'ga:users',
            'start-date': '7daysAgo',
            'end-date': 'yesterday'
        }
    });

    CurrentVisitorsData.on('success', function(response) {

        CurrentUsers = response.totalsForAllResults['ga:users'];
        console.log (CurrentUsers); //this displays the correct number of current users
    });

    CurrentVisitorsData.execute();

    console.log (currentUsers); // This one returns Uncaught ReferenceError: CurrentUsrs is not defined

});

因此,在響應函數中,變量有效,但之后不起作用。 我需要使用多個變量並對它們執行操作,因此我無法執行響應功能中需要做的事情。

知道如何在成功功能之外訪問該值嗎?

  1. 您聲明currentUsers而不是CurrentUsers,因此會引發錯誤。

  2. CurrentVisitorsData.on(...)是異步操作。 這是什么意思? 當您執行console.log(CurrentUsers); 未定義CurrentUsers,因為尚無值。 您應該將其傳遞給函數或回調。

=

function onResponseLoad(CurrentUsers){
  //do something with it
  console.log(CurrentUsers);
}

gapi.analytics.ready(function() {
  var CurrentUsers;
  var CurrentVisitorsData = new gapi.analytics.report.Data({
    query: {
      ids: 'ga:xxxxxx',
        metrics: 'ga:users',
        'start-date': '7daysAgo',
        'end-date': 'yesterday'
      }
  });

  CurrentVisitorsData.on('success', function(response) {
    CurrentUsers = response.totalsForAllResults['ga:users'];
    onResponseLoad(CurrentUsers);
  });

  CurrentVisitorsData.execute();
});

或使用IIFE和Promises(也許代碼看起來更好):

gapi.analytics.ready(function() {
  var CurrentUsers;

  var CurrentVisitorsData = new gapi.analytics.report.Data({
      query: {
        ids: 'ga:xxxxxx',
        metrics: 'ga:users',
        'start-date': '7daysAgo',
        'end-date': 'yesterday'
      }
    });

    (function getResponse(){
      return new Promise(function(resolve, reject){
        CurrentVisitorsData.on('success', function(response) {
          CurrentUsers = response.totalsForAllResults['ga:users'];
          resolve(CurrentUsers);
        });
      })
    })()
    .then(function(CurrentUsers){
      console.log(CurrentUsers);

    });

    CurrentVisitorsData.execute();
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM