angular2+ 里默认切换路由或者切换组件,页面的标题是不会变化的。 如果想针对每个路由设置页面标题,要使用 Title 服务,我们需要从 @angular/platform-browser 库导入 Title 类,然后利用 Angular 依赖注入的机制,通过构造注入的方式注入 Title 服务。其Title Service 提供了setTitle()和getTitle()方法。
1. route设置页面
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']));
}
}
网友评论