revolunet / angular-google-analytics

Google Analytics tracking for your AngularJS apps
MIT License
652 stars 172 forks source link

How to define different trackers for different environments via configuration #139

Closed santyclaz closed 8 years ago

santyclaz commented 8 years ago

So the problem I have is I have different environments for my app, each with a different tracker ID.

One solution I was thinking of would be to load the account information via configuration data that is retrieved asynchronously via AJAX request.

In the docs though, it gives me the impression the account can only be set during the config phase, so there isn't an opportunity for me to make an AJAX request to the server to retrieve configuration information.

AnalyticsProvider.setAccount([
   { tracker: 'UA-12345-12', name: "tracker1" },
   { tracker: 'UA-12345-34', name: "tracker2" }
]);

What would be the best way to go about solving my problem? Any better or recommended alternative solution is welcome as well.

Thanks!

justinsa commented 8 years ago

Hey @santyclaz, I actually had this exact scenario at the startup I was building last year. We opted to use a configuration file that we served to the client and loaded prior to loading the Angular components. The configuration.js contained all the necessary markers and created a window.configuration global. Our environments all had unique sub-domains so it was just a matter of checking the window.location.host value. So...

(function (window, _) {
  window.configuration = window.configuration || {};
  window.configuration.environment = {
    production: _.contain(['domain.com', 'www.domain.com'], window.location.host),
    staging: _.contain([`staging.domain.com`], window.location.host)
  };
  window.configuration.analytics = {
    tracker: `UA-12345-12`
  };
  if (window.configuration.environment.staging) {
    window.configuration.analytics.tracker = `UA-12345-34`;
  }
})(this, _);

You can then use this in your Angular code with the $window service, which is available during application configuration.

santyclaz commented 8 years ago

@justinsa thanks for sharing this alternative solution, I will likely use this strategy as that's the only solution I see right now.