import { Injectable , Inject } from '@angular/core' ; import { GtagPageview , GtagEvent , GtagConfig } from './interfaces' ; import { Router , NavigationEnd } from '@angular/router' ; import { tap , filter } from 'rxjs/operators' ; declare var gtag ; @ Injectable ( ) export class Gtag { private mergedConfig : GtagConfig ; constructor ( @ Inject ( 'config' ) gaConfig , private router ) { this . mergedConfig = { trackPageviews : true , ... gaConfig } ; if ( this . mergedConfig . trackPageviews ) { router . events . pipe ( filter ( event => event instanceof NavigationEnd ) , tap ( event => { this . pageview ( ) ; } ) ) . subscribe ( ) ; } } event ( action , params = { } ) { try { gtag ( 'event' , action , params ) ; this . debug ( 'event' , this . mergedConfig . trackingId , action , params ) ; } catch ( err ) { console . error ( 'Google Analytics event error' , err ) ; } } pageview ( params ? ) { try { const defaults = { page_path : this . router . url , page_title : 'Angular App' , page_location : window . location . href } ; params = { ... defaults , ... params } ; gtag ( 'config' , this . mergedConfig . trackingId , params ) ; this . debug ( 'pageview' , this . mergedConfig . trackingId , params ) ; } catch ( err ) { console . error ( 'Google Analytics pageview error' , err ) ; } } config ( params ) { try { gtag ( 'config' , this . mergedConfig . trackingId , ( params = { } ) ) ; } catch ( err ) { console . error ( 'Google Analytics config error' , err ) ; } } set ( params ) { try { gtag ( 'set' , ( params = { } ) ) ; } catch ( err ) { console . error ( 'Google Analytics set error' , err ) ; } } private debug ( ... msg ) { if ( this . mergedConfig . debug ) { console . log ( 'angular-gtag:' , ... msg ) ; } } }