Angular 2+ 监听路由变化动态设置页面标题

原网址:https://segmentfault.com/a/1190000009971757

路由配置代码:
const routes: Routes = [{ path: 'calendar', component: CalendarComponent, children: [ { path: '', redirectTo: 'new', pathMatch: 'full' }, { path: 'all', component: CalendarListComponent, data: { title: 'My Calendar' } }, { path: 'new', component: CalendarEventComponent, data: { title: 'New Calendar Entry' } }, { path: ':id', component: CalendarEventComponent, data: { title: 'Calendar Entry' } } ] }];



根组件设置代码:
import 'rxjs/add/operator/filter';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/mergeMap';

import { Component, OnInit } from '@angular/core';
import { Router, NavigationEnd, ActivatedRoute } from '@angular/router';
import { Title } from '@angular/platform-browser';

@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']));
  }
}

 

posted @ 2017-09-03 23:36  lyls  阅读(1989)  评论(0编辑  收藏  举报