All Downloads are FREE. Search and download functionalities are using the official Maven repository.

web.lib.core.analytics.segment-analytics.ts Maven / Gradle / Ivy

There is a newer version: 37
Show newest version
import _ from 'lodash';
import { Analytics } from './analytics';


import type { AnalyticsSnippet } from "@segment/analytics-next";

declare global {
    interface Window {
        analytics: AnalyticsSnippet;
    }
}

/**
 * In order to use this implementation, the following script need to be added to the index.html
 * 
 *
 */
export class SegmentAnalyticsImpl implements Analytics {

    private initialized:boolean = false;

    constructor(private readonly writeKey: string){}

    init(withPageView = true) {
      if(!window.analytics) {
          throw new Error("Unable to init Segment Analytics");
      }
      if(!this.initialized) {
          window.analytics.load(this.writeKey);
        withPageView && this.pageview(null);
        this.initialized = true;
      }
    }

    pageview(path: string) {
        window.analytics.page(path);
    }

    event(event: string, params?: object): void {
      _.defer(() => {
          window.analytics.track(event, {
              event,
              ...params
          })
      });
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy