UNPKG

@ngx-ext/google-analytics

Version:

Google Analytics for your Angular application

95 lines (89 loc) 3.17 kB
import { InjectionToken, EventEmitter, Injectable, Optional, Inject, NgModule } from '@angular/core'; import { ReplaySubject, timer, throwError, interval } from 'rxjs'; import { switchMap, takeUntil, filter, first, tap } from 'rxjs/operators'; const GA_TOKEN = new InjectionToken('Google Analytics TrackingId'); const GA_OPTIONS = new InjectionToken('Google Analytics Tracking Options'); class GoogleAnalyticsService { constructor(trackingId, options) { this.event = new EventEmitter(); this.pageView = new EventEmitter(); this.queue = new ReplaySubject(); if (trackingId) { this.configure(trackingId, options); } } configure(trackingId, options = 'auto') { this.ga('create', trackingId, options); this.ga('send', 'pageview'); this.event.subscribe((x) => { this.onEvent(x); }); this.pageView.subscribe((x) => { this.onPageView(x); }); const timer$ = timer(20000) .pipe(switchMap(() => throwError(new Error('Could not load GA')))); interval(50) .pipe(takeUntil(timer$), filter(() => Boolean(window.ga)), first(), switchMap(() => this.queue), tap(args => { window.ga(...args); // tslint:disable-line:no-unsafe-any })) .subscribe(); } set(key, value) { if (typeof key !== 'string' && typeof key !== 'object') { throw new TypeError(`Expected \`fieldName\` to be of type \`string\` or \`object\`, got \`${typeof key}\``); } if (typeof key === 'string' && value === undefined) { throw new TypeError('Expected `fieldValue` to not be `undefined`'); } if (typeof key === 'object') { this.ga('set', key); } else { this.ga('set', key, value); } } onEvent(event) { this.ga('send', 'event', event.category, event.action, event.label, event.value); } onPageView(pageview) { const fieldsObject = {}; if (pageview.title) { fieldsObject.title = pageview.title; } this.ga('send', 'pageview', pageview.page, fieldsObject); } ga(...args) { this.queue.next(args); } } GoogleAnalyticsService.decorators = [ { type: Injectable } ]; /** @nocollapse */ GoogleAnalyticsService.ctorParameters = () => [ { type: String, decorators: [{ type: Optional }, { type: Inject, args: [GA_TOKEN,] }] }, { type: undefined, decorators: [{ type: Optional }, { type: Inject, args: [GA_OPTIONS,] }] } ]; class GoogleAnalyticsModule { static forRoot() { return { ngModule: GoogleAnalyticsModule, providers: [ GoogleAnalyticsService, ], }; } } GoogleAnalyticsModule.decorators = [ { type: NgModule, args: [{ declarations: [], exports: [], imports: [], },] } ]; /** * Generated bundle index. Do not edit. */ export { GA_OPTIONS, GA_TOKEN, GoogleAnalyticsModule, GoogleAnalyticsService }; //# sourceMappingURL=ngx-ext-google-analytics.js.map