2017-08-16 9 views
0

私はカスタムアナリティクスダッシュボードを作成するためにGoogleAnalytics Embed APIを使用しています。Googleアナリティクスの値を変数にキャスト

現在、私のコードは次のようになります。

私の問題は、私は、他の計算で変数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 

}); 

変数作品だが、それはしていません後。複数の変数を使用して操作を実行する必要があるため、レスポンス関数で行う必要があることはできません。

私はsuccess関数の外でその値にどのようにアクセスできますか?

答えて

0
  1. 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(); 
}); 

または生命維持との約束を使用して(多分コードが良く見える):

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(); 
}); 
関連する問題