import { Title } from '@angular/platform-browser'; import {Component, OnInit} from '@angular/core'; import {Router, NavigationEnd, ActivatedRoute} from '@angular/router'; import 'rxjs/add/operator/filter'; import 'rxjs/add/operator/map'; @Component({}) export class AppComponent implements OnInit { constructor(private titleService: Title, private router: Router, private activatedRoute: ActivatedRoute) { // 使用this.title和this.router和this.activatedRoute到处浪 } ngOnInit() { this.router.events .filter(event => event instanceof NavigationEnd) .map(() => this.activatedRoute) // 将filter处理后的Observable再次处理 .subscribe((event) => { console.log('NavigationEnd:', event); }); } }
注意这里我们又使用了RxJS中的来更优雅地达成我们目的。
看起来我们已经完(luo)成(suo)很多事情了,但是还不够,我们目前还没有处理子路由,即我们上文路由配置中的children属性,所以我们还需要遍历路由表以便获取到每一个页面对应的路由信息:
ngOnInit() { this.router.events .filter(event => event instanceof NavigationEnd) .map(() => this.activatedRoute) .map((route) => { while(route.firstChild) { route = router.firstChild; } return route; }) .subscribe((event) => { console.log('NavigationEnd:', event); }); }
最后,我们还需要获取到我们在路由表中为每个路由传入的data信息,然后再利用Title Service设置页面标题:
ngOnInit() { this.router.events .filter(event => event instanceof NavigationEnd) .map(() => this.activatedRoute) .map(route => { while (route.firstChild) route = route.firstChild; return route; }) .mergeMap(route => route.data) .subscribe((event) => this.titleService.setTitle(event['title'])); }
下面是完成的最终代码,或者也可以到GitHub上查看完整代码:
import { Component, OnInit } from '@angular/core'; import { Router, NavigationEnd, ActivatedRoute } from '@angular/router'; import { Title } from '@angular/platform-browser'; import 'rxjs/add/operator/filter'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/mergeMap'; @Component({...}) export class AppComponent implements OnInit { constructor( private router: Router, private activatedRoute: ActivatedRoute, private titleService: 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.titleService.setTitle(event['title'])); } }
参考文档