问题
I am using the following code to embed Google Analytics api into my Angular 2 app:
Mycomponent.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>
Replaced My-Client-Id with Google client Id and in index.html added loading platform.js code in tag as below:
<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>
I have tested the same code in jQuery based application which is working fine but its showing blank page in Angular2 app with no JavaScript console errors.
I have added the website to authorized JavaScript origin as well. Is there any other configurations do we need to do for Angular2 app?
For your information,I have created oAuth Client ID, enabled the Analytics API, added website to authorized JavaScript origin and disabled my adblocker.
来源:https://stackoverflow.com/questions/43322623/google-analytics-embed-api-not-working-on-angular-2-app