3

我想知道将 Google Analytic 集成到我的 AngularJS 应用程序中的正确方法。我想通过 DI 提供它,所以我可以在单元测试期间模拟它,并测试哪些数据正在发送给它。

我正在尝试这样的事情:

.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;
})

但是当然它不起作用,因为 first 是一个虚拟对象,并且在analytics.js加载时,用正确的实现替换window.qa(即:)。window[document['GoogleAnalyticsObject']]因此,当服务运行时,返回虚拟实现。

我想使用提供者将是正确的方法,因为我还想配置一些参数(如 UserID 等),但我不知道如何设置它。

哪种方法是正确的?

4

1 回答 1

0

This is the best I got so far:

.provider('$ga', function () {

    window['GoogleAnalyticsObject'] = 'ga';
    window['ga'] = window['ga'] || function () { (window['ga'].q = window['ga'].q || []).push(arguments)}
    window['ga'].l = 1 * new Date();
    var script = document.createElement('script');
    var prevScript = document.getElementsByTagName('script')[0];
    script.async = 1;
    script.src = '//www.google-analytics.com/analytics.js';
    prevScript.parentNode.insertBefore(script, prevScript);

    var provider = function () {
        var me = {};

        me.$get = function () {
            ga('send', 'pageview');
            return function () {                
                return window.ga.apply(window, arguments);
            }
        };

        me.ga = function () {
                return window.ga.apply(window, arguments);
        };

        return me;
    };

    return provider();
})

It is a provider that can be configured:

.config(['$gaProvider',function ($gaProvider) {
    $gaProvider.ga('create','UA-XXXXXX-Y','auto');
}])

Feedback is welcomed.

于 2014-07-30T09:47:00.560 回答