Angular 中浏览器显示和 Google 分析的动态页面标题

Dynamic Page Title for both browser display and Google Analytics in Angular

问题是:

如何在 Angular 应用程序中动态集中设置页面标题一次,用于两个目的:

我目前的解决方案

我使用了在 Github 上找到的两个不错的片段:

  • first 允许在路由器配置中集中定义页面标题,仅用于视觉目的,
  • second provides a solution for sending navigation events to Google Analytics, while within a Single Page Application - in an automatic centralised way or manually. It's received an inspiring ticket commented by amarnathm

嗯,那两个中提出的想法,包括对 issue 报告给后者的讨论,可以这样整合:

app.routing-module.ts:

const routes: Routes = [ 
  { path: 'site/contact', component: ContactComponent, data: {title: 'Contact'}},
  ...
  // other paths
];

app.module.ts:

import {BrowserModule} from '@angular/platform-browser';
import {TitleService} from "./title.service";
import {GtagModule} from "angular-gtag";
// ...
providers: [
    // ...
    TitleService,
    GtagModule.forRoot({ trackingId: 'MY-UA-CODE', trackPageviews: false })        
    // ...   
  ]
// ...

trackPageviews: false,按照amarnathm, is important as we'll track manually per page. Standard sample code by Jeff的建议,默认为true

title.service.ts:

import { Injectable } from '@angular/core';
import { Router, ActivatedRoute, NavigationEnd } from '@angular/router';
import { Title } from '@angular/platform-browser';
import { filter, map, switchMap } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class TitleService {
  default_title = 'My App';

  constructor(
    private router: Router,
    private activeRoute: ActivatedRoute,
    private title: Title,
    private gtag: Gtag,
    private env: Environment
  ) { }

  boot() {
    this.router.events.pipe(
      filter(event => event instanceof NavigationEnd),
      map(() => this.activeRoute),
      map(route => route.firstChild),
      switchMap(route => route.data),
      map((data) => {

        //here goes the GA reporting code            

        this.gtag.pageview({
          page_title: data && data.title ? data.title : this.default_title,
          page_path: this.router.url,
          page_location: this.env.host + this.router.url
        });

        return data && data.title ? `${data.title} • ${this.default_title}` : this.default_title;
      })
    ).subscribe((current_title) => this.title.setTitle(current_title));
  }
}

app.component.ts:

import { Component, OnInit } from '@angular/core';
import { TitleService } from './title.service';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styles: [],
})
export class AppComponent implements OnInit {

  constructor(private titleService: TitleService) { }

  ngOnInit() {
    this.titleService.boot();
  }
}

删除 index.html 文件中可能存在的任何 GA/Gtag 代码。这允许自定义订阅 GA 服务,而无需依赖我们不会使用的自动跟踪。在 SPA 中 index.html 通常加载一次并且没有设置页面跟踪是无用的。

增强建议:

我没有得到答案:

How to make use of ActivatedRoute parameters and map them to detailed titles used then in Analytics and optionally - for displaying per parameter titles in a browser.