为了两个目的,如何在 Angular App 中动态集中设置页面标题一次:
我使用了 Github 上的两个不错的片段:
那么,这两个中提出的想法,包括对向后者报告的问题的讨论,可以通过这种方式进行整合:
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
标题.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 服务,而无需依赖我们不会使用的自动跟踪。在 SPAindex.html
中通常加载一次并且没有页面跟踪设置是无用的。
我没有答案:
如何使用
ActivatedRoute
参数并将它们映射到随后在 Analytics 中使用的详细标题,以及可选 - 用于在浏览器中显示每个参数的标题。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句