小编Leo*_*ira的帖子

Angular 4+使用Google Analytics

我正在尝试使用角度为4的Google Analytics,但我在ts中找不到任何@type到ga.js.

为了快速解决方案,我在每个组件中使用了它:

declare let ga: any;
Run Code Online (Sandbox Code Playgroud)

按照我如何解决它:

创建一个动态加载GA的函数,将GA脚本与当前的trackingId和user一起插入.

    loadGA(userId) {
        if (!environment.GAtrackingId) return;

        let scriptId = 'google-analytics';

        if (document.getElementById(scriptId)) {
            return;
        }

        var s = document.createElement('script') as any;
        s.type = "text/javascript";
        s.id = scriptId;
        s.innerText = "(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', { trackingId: '" + **environment.GAtrackingId** + "', cookieDomain: 'auto', userId: '" + **userId** + "'});ga('send', 'pageview', '/');";

        document.getElementsByTagName("head")[0].appendChild(s);
    }
Run Code Online (Sandbox Code Playgroud)

创建服务以实现您需要的方法.

import { Injectable } from '@angular/core';
import { environment } from '../../../environments/environment';

declare let ga: any;

@Injectable()
export class GAService { …
Run Code Online (Sandbox Code Playgroud)

google-analytics typescript typescript-typings angular

52
推荐指数
5
解决办法
4万
查看次数