typescript - Angular 4+ using Google Analytics -
i'm trying use google analytics angular 4, can't find @type ga.js in ts.
for quick solution used in every component:
declare let ga: any;
following how resolved it:
create function load ga dynamically inserts ga script current trackingid , user.
loadga(userid) { if (!environment.gatrackingid) return; let scriptid = 'google-analytics'; if (document.getelementbyid(scriptid)) { return; } var s = document.createelement('script') 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); }
create service implement methods need.
import { injectable } '@angular/core'; import { environment } '../../../environments/environment'; declare let ga: any; @injectable() export class gaservice { constructor() { } /** * checks if ga script loaded. */ private usega() : boolean { return environment.gatrackingid && typeof ga !== undefined; } /** * sends page view ga. * @param {string} page path portion of url. value should start slash (/) character. */ sendpageview( page: string ) { if (!this.usega()) return; if (!page.startswith('/')) page = `/${page}`; ga('send', 'pageview', page); } /** * sends event ga. * @param {string} eventcategory typically object interacted (e.g. 'video') * @param {string} eventaction type of interaction (e.g. 'play') */ sendevent( eventcategory: string, eventaction: string ) { if (!this.usega()) return; ga('send', 'event', eventcategory, eventaction); } }
then use service injected in component.
constructor(private ga: gaservice) {} ngoninit() { this.ga.sendpageview('/join'); }
Comments
Post a Comment