最佳答案
我试图使用谷歌分析与角4,但我不能找到任何@类型,以 ga.js 在 t。
为了获得快速解决方案,我在每个组件中都使用了这种方法:
declare let ga: any;
我是这么解决的:
创建一个动态加载 GA 的函数,插入带有当前 trackingId 和用户的 GA 脚本。
loadGA(userId) {
if (!environment.GAtrackingId) return;
let scriptId = 'google-analytics';
if (document.getElementById(scriptId)) {
return;
}
var s = document.createElement('script') as any;
s.type = "text/javascript";
s.id = scriptId;
s.innerText = "(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)})(window,document,'script','//www.google-analytics.com/analytics.js','ga');ga('create', { trackingId: '" + **environment.GAtrackingId** + "', cookieDomain: 'auto', userId: '" + **userId** + "'});ga('send', 'pageview', '/');";
document.getElementsByTagName("head")[0].appendChild(s);
}
创建服务以实现您将需要的方法。
import { Injectable } from '@angular/core';
import { environment } from '../../../environments/environment';
declare let ga: any;
@Injectable()
export class GAService {
constructor() {
}
/**
* Checks if the GA script was loaded.
*/
private useGA() : boolean {
return environment.GAtrackingId && typeof ga !== undefined;
}
/**
* Sends the page view to GA.
* @param {string} page The path portion of a URL. This value should start with a slash (/) character.
*/
sendPageView(
page: string
) {
if (!this.useGA()) return;
if (!page.startsWith('/')) page = `/${page}`;
ga('send', 'pageview', page);
}
/**
* Sends the event to GA.
* @param {string} eventCategory Typically the object that was interacted with (e.g. 'Video')
* @param {string} eventAction The type of interaction (e.g. 'play')
*/
sendEvent(
eventCategory: string,
eventAction: string
) {
if (!this.useGA()) return;
ga('send', 'event', eventCategory, eventAction);
}
}
然后最后使用组件中注入的服务。
constructor(private ga: GAService) {}
ngOnInit() { this.ga.sendPageView('/join'); }