angularmixpanel

Integrate mixpannel with Angular 5


I want to integrate mixpannel to my Angular app. I couldn't find a package or straight forward answer for this. Can anyone give me a link to good tutorial or code to integrate mixpannel.

Thanks in advance.


Solution

  • install mixpanel-browser

    npm install --save mixpanel-browser
    

    and types

    npm install --save @types/mixpanel-browser
    

    Add the tracking code to index.html

        <!-- start Mixpanel -->
        <script type="text/javascript">
            (function(e,b){if(!b.__SV){var a,f,i,g;window.mixpanel=b;b._i=[];b.init=function(a,e,d){function f(b,h){var a=h.split(".");2==a.length&&(b=b[a[0]],h=a[1]);b[h]=function(){b.push([h].concat(Array.prototype.slice.call(arguments,0)))}}var c=b;"undefined"!==typeof d?c=b[d]=[]:d="mixpanel";c.people=c.people||[];c.toString=function(b){var a="mixpanel";"mixpanel"!==d&&(a+="."+d);b||(a+=" (stub)");return a};c.people.toString=function(){return c.toString(1)+".people (stub)"};i="disable time_event track track_pageview track_links track_forms register register_once alias unregister identify name_tag set_config people.set people.set_once people.increment people.append people.union people.track_charge people.clear_charges people.delete_user".split(" ");
            for(g=0;g<i.length;g++)f(c,i[g]);b._i.push([a,e,d])};b.__SV=1.2;a=e.createElement("script");a.type="text/javascript";a.async=!0;a.src="undefined"!==typeof MIXPANEL_CUSTOM_LIB_URL?MIXPANEL_CUSTOM_LIB_URL:"file:"===e.location.protocol&&"//cdn.mxpnl.com/libs/mixpanel-2-latest.min.js".match(/^\/\//)?"https://cdn.mxpnl.com/libs/mixpanel-2-latest.min.js":"//cdn.mxpnl.com/libs/mixpanel-2-latest.min.js";f=e.getElementsByTagName("script")[0];f.parentNode.insertBefore(a,f)}})(document,window.mixpanel||[]);
        </script>
        <!-- end Mixpanel -->
    

    Add mixpanel token in environment files and create a wrapper service for Mixpanel events.

        import { Injectable } from '@angular/core';
        import { environment } from './environments/environment';
        import * as mixpanel from 'mixpanel-browser';
        
        
        @Injectable()
        export class MixpanelService {
          private mixpanelToken: string;
        
          /**
           * constructor
           * get mixpanel token and initialize
           */
          constructor() {
            this.mixpanelToken = environment.mixpanel_token;
        
            this.init();
          }
        
          /**
           * Initialize mixpanel.
           */
          init(): void {
            mixpanel.init(this.mixpanelToken);
          }
        
        
         /**
           * Create new Alias for user
           * Call this method only once in user lifecycle
           *
           * @param {string} alias
           */
          createAlias(alias: string) {
            mixpanel.alias(alias, mixpanel.get_distinct_id());
          }
        
          /**
           * Identify User
           *
           * @param {string} alias
           */
          identify(alias: string) {
            mixpanel.identify(alias);
          }
        
          /**
           * Push new action to mixpanel.
           *
           * @param {string} id Name of the action to track.
           * @param {*} [action={}] Actions object with custom properties.
           * @memberof MixpanelService
           */
          track(id: string, action: any = {}): void {
            mixpanel.track(id, action);
          }
        
          /**
           * setup mixpannel
           *
           */
          setup() {
            mixpanel.loggingEnabled = false;
            this.setSuperProperties({ Platform: 'web' });
          }
        
         /**
           * setPeople
           * Store user profiles in Mixpanel's People Analytics product
           * @param {Object} properties
           */
          setPeople(properties: any = {}): void {
            mixpanel.people.set(properties);
          }
        
          /**
           * setSuperProperties
           *
           * @param {object} properties
           */
          setSuperProperties(properties) {
            mixpanel.register(properties);
          }
        
          /**
           * sendEvent
           *
           * @param {string} event
           * @param {object} properties
           */
          sendEvent(event: string, properties?) {
            if (properties) {
              mixpanel.track(event, properties);
            } else {
              this.trackEvent(event);
            }
          }
        
          /**
           * trackEvent
           * @param {string} event
           */
          trackEvent(event: string) {
            mixpanel.track(event);
          }
        
          /**
           * Reset Mixpanel
           */
          logout() {
            mixpanel.reset();
          }
        
        }
    

    Now use this mixpanel service any where.

        constructor(private mixpanelService: MixpanelService) {}
        
        trackFunctionInComponent() {
          this.mixpanelService.track('Track action', {
            propertyOne: 'valueOne',
            propertyTwo: 'valueTwo'
          });
        }