angular2+ 里默認(rèn)切換路由或者切換組件训貌,頁面的標(biāo)題是不會變化的。 如果想針對每個路由設(shè)置頁面標(biāo)題,要使用 Title 服務(wù)漓骚,我們需要從 @angular/platform-browser 庫導(dǎo)入 Title 類,然后利用 Angular 依賴注入的機制榛泛,通過構(gòu)造注入的方式注入 Title 服務(wù)蝌蹂。其Title Service 提供了setTitle()和getTitle()方法。
1. route設(shè)置頁面
import { Routes } from '@angular/router';
import { HeroesComponent } from './heroes/heroes.component';
import { HomeComponent } from './home/home.component'
export const rootRouterConfig: Routes = [
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{ path: 'home', component: HomeComponent, data: { title: 'Home-Liu' } },
{ path: 'heroes', component: HeroesComponent, data: { title: 'heros-Liu' } }
]
2. app.component.ts頁面
import 'rxjs/add/operator/filter';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/mergeMap';
import { Router, NavigationEnd, ActivatedRoute } from '@angular/router';
import { Title } from '@angular/platform-browser';
export class AppComponent {
constructor(
private router: Router,
private activatedRoute: ActivatedRoute,
private title: Title
) { }
ngOnInit() {
this.router.events
.filter(event => event instanceof NavigationEnd)
.map(() => this.activatedRoute)
.map(route => {
while (route.firstChild) route = route.firstChild;
return route;
})
.filter(route => route.outlet === 'primary')
.mergeMap(route => route.data)
.subscribe((event) => this.title.setTitle(event['title']));
}
}