将Google Analytics(分析)添加到具有不同环境的Angular 5项目中

时间:2019-03-26 23:19:08

标签: javascript angular google-analytics

我正在使用Angular 5,并且想要添加Google Analytics(分析)。

已经有很多关于此的教程,例如:

我看过的所有教程都需要在index.html中添加以下代码:

index.html

      constructor(private _fb: FormBuilder, private firmService: FirmService,
                     private commonDataService: CommonDataService, private notify: NotifyService,private changeDetectorRef: ChangeDetectorRef) {

                       // this.changeDetectorRef.markForCheck();
        }

        ngOnInit() {
            this.initializeFormModel();
            this.getFirmDetails();
        }


        initializeFormModel() {
            this.frmFirm = this._fb.group({
                FirmName: [''],
                DateFounded: [''],
                Websites: this._fb.array([
                    this.createWebsite()
                ])

            });
        }


        public addWebsite(): void {
            this.Websites.push(this.createWebsite());
            this.frmFirm.setErrors({'dirty': false});
        }


        public removeWebsite(index: number): void {
            const websites = this.frmFirm.get('Websites') as FormArray;
            if (websites.length === 1)
            {
                websites.reset();
              return;
            }
            websites.removeAt(index);
            this.frmFirm.setErrors({'dirty': true});
        }


        private createWebsite(): FormGroup {
            return this._fb.group({
                WebsiteUrl: ['', Validators.required],
                Username: [''],
                Password: ['']
            });
        }

         get Websites(): FormArray {
            return <FormArray>this.frmFirm.get('Websites');
        }


     const websiteGroup = FirmDetails.Websites.map(website => {
               return this._fb.group({
                FirmWebsiteId:    [website.FirmWebsiteId],
                WebsiteUrl: [website.WebsiteUrl],
                Username:   [website.Username],
                Password:   [website.Password],
                FirmId: [website.FirmId]
                });
            });
            const wesbiteFormArray: FormArray = this._fb.array(websiteGroup);
            this.frmFirm.setControl('Websites', wesbiteFormArray);
        }

        getFirmDetails() {
              if (this.FirmId != null) {
                this.firmService.getFirmDetails(this.FirmId).subscribe((data: any) => {
                    this.FirmDetails = data;
                    this.FirmId = this.FirmDetails.FirmId;
                    this.setFormValues(this.FirmDetails);
                    this.EditMode = false;
                    this.changeDetectorRef.markForCheck();

                });
            } else {
                this.FirmDetails = {};
                this.EditMode = true;
            }
        }

问题出在那行:

...
<app-root></app-root>
<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-109919601-1', 'auto'); // add your tracking ID here. ISSUE HERE!
ga('send', 'pageview');
</script>
...

我想根据自己所处的环境使用其他跟踪代码。 我该怎么办?

一些解决方案建议将此代码添加到Angular代码中,如下所示:

ga('create', 'UA-109919601-1', 'auto');

该解决方案的问题在于Google Analytics(分析)的运行速度不够快,从而影响了加载时间分析。

感谢您的帮助:-)

1 个答案:

答案 0 :(得分:2)

index.html

注释以下几行:

ga('create', 'UA-XXXXXX-X', 'auto'); 
ga('send', 'pageview');

app.component.ts

将跟踪ID作为environment.ts添加到您的gaTrackingId文件中。

在构造函数中放置以下代码:

this.router.events.subscribe(event => {
  if (event instanceof NavigationEnd) {
    (<any>window).ga('create', environment.gaTrackingId, 'auto');
    (<any>window).ga('set', 'page', event.urlAfterRedirects);
    (<any>window).ga('send', 'pageview');
  }
});