zoukankan      html  css  js  c++  java
  • 在像Angular2这样的SPA应用中使用Google Analytics的方法

    Angular2のようなシングルページアプリケーションでGoogleアナリティクスを使う方法

    如何在像Angular2这样的SPA应用中使用Google Analytics?

    试着调查了一下。

    由于SPA的特性,在每页中粘贴Analytics代码会出岔子的。那么怎么做呢?

    <!doctype html>
    <html>
    <head>
      <meta charset="utf-8">
      <title>LotsJOY</title>
      <base href="/">
    
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <link rel="icon" type="image/x-icon" href="favicon.ico">
      <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
      <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
      <script>
        (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','https://www.google-analytics.com/analytics.js','ga');
    
        ga('create', 'UA-72706518-3', 'auto');
        // ga('send', 'pageview');
    
      </script>
    
    
    </head>
    <body>
      <app-root>Loading...</app-root>
    </body>
    </html>
    

    首先,在index.html的<head>中加上Analytics代码。

    接着,在app.component.ts中追加这样的代码:

    import { Component } from '@angular/core';
    import {Router, NavigationEnd} from "@angular/router";
    declare var ga: any;
    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
    })
    export class AppComponent {
     constructor(public router: Router){
       router.events.distinctUntilChanged((previous: any, current: any) => {
         if(current instanceof NavigationEnd) {
           return previous.url === current.url;
         }
         return true;
       }).subscribe((x: any) => {
       //  console.log('router.change', x);
         ga('send', 'pageview', x.url);
       });
     }
    }
    declare var ga: any; 叫作环境声明。将其他的组件(Web浏览器和既存的JavaScript库)提供的变量和函数等等传达给TypeScript的编译器。
    这个是添加既存的JavaScript库的静态类型,使得在TypeScript中可以使用它的意思。
    也就是,声明在TypeScript中可以使用Google Analytics代码中的ga变量。

    router.events.distinctUntilChanged这部分是检测路由上的变化,确认路由确实变化后,向Google发送新的路径。
    
    
  • 相关阅读:
    洛谷 P4160 [SCOI2009]生日快乐 题解
    洛谷 P1041 传染病控制 题解
    洛谷 P3154 [CQOI2009]循环赛 题解
    洛谷 P1144 最短路计数 题解
    洛谷 P2296 寻找道路 题解
    洛谷 P1514 引水入城 题解
    洛谷 P2661 信息传递 题解
    洛谷 P3958 奶酪 题解
    洛谷 P3501 [POI2010]ANT-Antisymmetry 题解
    【LGR-069】洛谷 2 月月赛 II & EE Round 2 Div.2 A-C题解
  • 原文地址:https://www.cnblogs.com/niaomingjian/p/7684975.html
Copyright © 2011-2022 走看看