我使用以下代码将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,并在索引中.html添加了加载平台.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,启用了分析API,将网站添加到授权的JavaScript源并禁用了我的广告拦截器。
组件 HTML 文件中的脚本标记按角度自动剥离
因此,您需要将 gapi.analytics.ready 函数移动到 ngOnInit(( 函数中的 Mycomponent.ts 文件中。
index.html文件中的脚本标记很好,可以保留。