我使用以下代码将Google Analytics API嵌入到我的Angular 2应用中:
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>
将My-Client-Id替换为Google客户端ID,并在index.html中添加了loading platform.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 app做任何其他配置吗?
为了您的信息,我创建了oAuth客户端ID,启用了Analytics API,将网站添加到授权的JavaScript源,并禁用了我的广告拦截器。
答案 0 :(得分:2)
组件HTML文件中的脚本标签为automatically stripped by angular
因此,您需要将ngOnInit()函数中的gapi.analytics.ready函数移至Mycomponent.ts文件中。
index.html文件中的script标签很好,您可以保留它。