一般情况下在页面修改标题需要在每个页面组件里引入:
import { Title } from '@angular/platform-browser';
constructor(
private titleService: Title
) { }
this.titleService.setTitle("title");
但是,在每个页面都写一次是不是很繁琐呢,也不利于管理标题。可以将设定标题封装成一个services服务,达到统一修改title的目的。
1. 修改页面入口文件index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>{{title}}</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
<app-root></app-root>
</body>
</html>
2. 配置页面的路由,设置data属性中的title
const routes: Routes = [
{ path: '', redirectTo: '/login', pathMatch: 'full' },
{ path: 'login', component : LoginComponent , data : { title : "登录" }},
{ path: 'index', loadChildren: () => import('./pages/index/index.module').then(m => m.IndexModule), data : { title : "首页" } },
{ path: '**', component: NotFoundComponent , data : { title : "404" }}
];
3.创建一个公共服务CommonService
import { Injectable } from '@angular/core';
import { Router, NavigationEnd, ActivatedRoute } from '@angular/router';
import { Title } from '@angular/platform-browser';
import { map, filter } from "rxjs/operators";
@Injectable({
providedIn: 'root'
})
export class CommonService {
constructor(
private router: Router,
private titleService: Title
) {}
public setTitle() {
this.router.events.pipe(
filter(event => event instanceof NavigationEnd),
map(() => this.router)
)
.subscribe((event) => {
const titles = this.getTitle(this.router.routerState, this.router.routerState.root);
const title = titles[titles.length - 1];
// console.log(title);
if (title) {
this.titleService.setTitle(title);
}
});
}
public getTitle(state, parent) {
const data = [];
if (parent && parent.snapshot.data && parent.snapshot.data.title) {
data.push(parent.snapshot.data.title);
}
if (state && parent) {
data.push(...this.getTitle(state, state.firstChild(parent)));
}
return data;
}
}
4.在根模块app.component.ts
中调用
引用注入公共服务CommonService,并调用
setTitle设置title
import { Component } from '@angular/core';
import { CommonService } from "@services/common.service";
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.less']
})
export class AppComponent {
constructor(
private common: CommonService
) { }
ngOnInit() {
//设置页面标题
this.common.setTitle();
}
}