Tracking Google Analytics Page Views in Angular2

前端 未结 6 1776
一个人的身影
一个人的身影 2020-12-04 11:16

I have built a new site using Angular 2 as the front-end. As everything is done via push state, there are no page loads which typically trigger the Google Analytics code to

6条回答
  •  既然无缘
    2020-12-04 12:05

    Expanding on Ian's answer. You can use Rx's built in features to handle the distinction between current and new routes.

    import { NavigationEnd, Router } from '@angular/router';
    
    declare var ga: any;
    
    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);
                });
            }
        }
    

    We are using the distinctUntilChanged operator to make the observer only emit items that are of type NavigationEnd and do not have the same route as the previously emitted item.

提交回复
热议问题