I am wondering which is the right way of integrating Google Analytic into my AngularJS app. I would like to provide it through DI, so I can mock it during unit testing, and test which data is being sent to it.
I was trying something like this:
.service('$ga', function () {
(function (i, s, o, g, r, a, m) {
i['GoogleAnalyticsObject'] = r;
i[r] = i[r] || function () {
(i[r].q = i[r].q || []).push(arguments)
},
i[r].l = 1 * new Date();
a = s.createElement(o),
m = s.getElementsByTagName(o)[0];
a.async = 1;
a.src = g;
m.parentNode.insertBefore(a, m);
})(window, document, 'script', '//www.google-analytics.com/analytics.js', 'ga');
ga('create', 'GA_KEY', 'auto');
ga('send', 'pageview');
return ga;
})
But of course it does not work, since first is a dummy object and when analytics.js
loads, replaces window.qa
(ie:window[document['GoogleAnalyticsObject']]
) with the proper implementation. So when the service runs, returns the dummy implementation.
I guess that using a provider will be the right way, since I would like to also configure some parameters (like UserID, etc...), but I have no idea how to set it up that way.
Which is the right approach?