动态页面标题,用于浏览器显示和 Google Analytics in Angular



问题是:

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

  • 要使浏览器中的标题反映实际访问的页面,
  • 将特定标题发送到Google Analytics,避免将无聊,单一和无用的Angular应用程序描述应用于所有应用程序的页面。

我当前的解决方案

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

  • 首先允许在路由器配置中集中定义页面标题,仅用于视觉目的,
  • 第二个提供了一个解决方案,用于在单页应用程序中以自动集中方式或手动向Google Analytics发送导航事件。它收到了一张由 amarnathm 评论的鼓舞人心的票证。

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

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 所提议的那样,这很重要,因为我们将按页面手动跟踪。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通常加载一次,没有设置页面跟踪是无用的。

优化建议:

我没有答案:

如何使用ActivatedRoute参数并将其映射到 详细标题随后在 Analytics 中使用,并可选择用于显示浏览器中的每个参数标题。

最新更新