From 99ae96d4635dff1953769ac692d9e17e14f072e5 Mon Sep 17 00:00:00 2001 From: Mihai Stanescu Date: Thu, 8 Feb 2018 11:55:48 +0200 Subject: [PATCH] Add the posibility to send events to a named tracker. Reference here: https://developers.google.com/analytics/devguides/collection/analyticsjs/accessing-trackers --- package.json | 2 +- src/lib/ga.service.ts | 21 ++++++++++++++++----- src/lib/interfaces/tracking-options.ts | 1 + 3 files changed, 18 insertions(+), 6 deletions(-) diff --git a/package.json b/package.json index ffe16fb..96ac4e2 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "angular-ga", - "version": "1.0.0", + "version": "1.0.1", "description": "Google Analytics for your Angular application", "license": "MIT", "repository": "SamVerschueren/angular-ga", diff --git a/src/lib/ga.service.ts b/src/lib/ga.service.ts index 02a8787..41573f7 100644 --- a/src/lib/ga.service.ts +++ b/src/lib/ga.service.ts @@ -11,6 +11,8 @@ declare const ga: any; export class GoogleAnalyticsService { event = new EventEmitter(); pageview = new EventEmitter(); + sendCommand: string = 'send'; + setCommand: string = 'set'; constructor( @Optional() @Inject(GA_TOKEN) trackingId: string, @@ -22,8 +24,17 @@ export class GoogleAnalyticsService { } configure(trackingId: string, options: TrackingOptions | string = 'auto') { + if (typeof options === 'object' && options.namedTracker) { + if (typeof options.name === 'string' && !options.name) { + throw new TypeError('Expected `options.name` to not be `undefined`'); + } + + this.sendCommand = options.name + '.send'; + this.setCommand = options.name + '.set'; + } + ga('create', trackingId, options); - ga('send', 'pageview'); + ga(this.sendCommand, 'pageview'); this.event.subscribe((x: Event) => this.onEvent(x)); this.pageview.subscribe((x: PageView) => this.onPageView(x)); @@ -41,14 +52,14 @@ export class GoogleAnalyticsService { } if (typeof key === 'object') { - ga('set', key); + ga(this.setCommand, key); } else { - ga('set', key, value); + ga(this.setCommand, key, value); } } private onEvent(event: Event) { - ga('send', 'event', event.category, event.action, event.label, event.value); + ga(this.sendCommand, 'event', event.category, event.action, event.label, event.value); } private onPageView(pageview: PageView) { @@ -58,6 +69,6 @@ export class GoogleAnalyticsService { fieldsObject.title = pageview.title; } - ga('send', 'pageview', pageview.page, fieldsObject); + ga(this.sendCommand, 'pageview', pageview.page, fieldsObject); } } diff --git a/src/lib/interfaces/tracking-options.ts b/src/lib/interfaces/tracking-options.ts index 0a3855a..2af8575 100644 --- a/src/lib/interfaces/tracking-options.ts +++ b/src/lib/interfaces/tracking-options.ts @@ -1,5 +1,6 @@ export interface TrackingOptions { name?: string; + namedTracker: boolean; storage?: string; clientId?: string; sampleRate?: number;