angular-ga
Version:
Google Analytics for your Angular application
98 lines (92 loc) • 3.42 kB
JavaScript
import { __decorate, __param } from 'tslib';
import { InjectionToken, EventEmitter, Optional, Inject, Injectable, 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('angular-ga TrackingId');
const GA_OPTIONS = new InjectionToken('angular-ga Tracking Options');
let GoogleAnalyticsService = 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.ctorParameters = () => [
{ type: String, decorators: [{ type: Optional }, { type: Inject, args: [GA_TOKEN,] }] },
{ type: undefined, decorators: [{ type: Optional }, { type: Inject, args: [GA_OPTIONS,] }] }
];
GoogleAnalyticsService = __decorate([
Injectable(),
__param(0, Optional()), __param(0, Inject(GA_TOKEN)),
__param(1, Optional()), __param(1, Inject(GA_OPTIONS))
], GoogleAnalyticsService);
var GoogleAnalyticsModule_1;
let GoogleAnalyticsModule = GoogleAnalyticsModule_1 = class GoogleAnalyticsModule {
static forRoot() {
return {
ngModule: GoogleAnalyticsModule_1,
providers: [
GoogleAnalyticsService
]
};
}
};
GoogleAnalyticsModule = GoogleAnalyticsModule_1 = __decorate([
NgModule({
imports: [],
declarations: [],
exports: []
})
], GoogleAnalyticsModule);
/**
* Generated bundle index. Do not edit.
*/
export { GA_OPTIONS, GA_TOKEN, GoogleAnalyticsModule, GoogleAnalyticsService };
//# sourceMappingURL=angular-ga.js.map