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

前端之家收集整理的这篇文章主要介绍了Angular 2+ 监听路由变化动态设置页面标题前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

现在很多web网站都采用了SPA单页应用,单页面有很多优点:用户体验好、应用响应快、对服务器压力小 等等。同时也有一些缺点:首次加载资源太多,不利于SEO,前进、后退、地址栏需要手动管理。今天我们实现Angular页面应用中路由变化设置页面标题,来优化用户用户体验。可以先去掘金看下效果稀土掘金

在AngularJS(1.x)中动态设置页面标题通常是通过一个全局$rootScope对象来完成的,通过$rootScope对象监听路由变化获取当前路由信息并映射到页面标题。在Angular(v2 +)中,解决起来要比1.x容易得多,我们可以通过注入一个provider,在路由变化事件中使用provider提供的API来动态更新页面标题

Title Service

在angular中,我们可以通过Title来设置页面标题。我们从platform-browser导入Title,同时也导入Router

  1. import { Title } from '@angular/platform-browser';
  2. import { Router } from '@angular/router';

导入之后,我们在组件的构造函数中注入他们

  1. @Component({
  2. selector: 'app-root',templateUrl: `
  3. <div>
  4. Hello world!
  5. </div>
  6. `
  7. })
  8. export class AppComponent {
  9. constructor(private router: Router,private titleService: Title) {}
  10. }

在使用Title之前,我们先看下Title是如何定义的

  1. export class Title {
  2. /**
  3. * Get the title of the current HTML document.
  4. * @returns {string}
  5. */
  6. getTitle(): string { return getDOM().getTitle(); }
  7.  
  8. /**
  9. * Set the title of the current HTML document.
  10. * @param newTitle
  11. */
  12. setTitle(newTitle: string) { getDOM().setTitle(newTitle); }
  13. }

Title类有两个方法,一个用来获取页面标题getTitle, 一个是用来设置页面标题setTitle

要更新页面标题,我们可以简单的调用setTitle方法:

  1. @Component({...})
  2. export class AppComponent implements OnInit {
  3. constructor(private router: Router,private titleService: Title) {}
  4. ngOnInit() {
  5. this.titleService.setTitle('My awesome app');
  6. }
  7. }

这样就可以设置我们的页面标题了,但是很不优雅。我们接着往下看。

在AngularJS中,我们可以使用ui-router为每个路由添加一个自定义对象,自定义的对象在路由器的状态链中继承:

  1. // AngularJS 1.x + ui-router
  2. .config(function ($stateProvider) {
  3. $stateProvider
  4. .state('about',{
  5. url: '/about',component: 'about',data: {
  6. title: 'About page'
  7. }
  8. });
  9. });

在Angular2+中,我们也可以为每个路由定义一个data对象,然后再在监听路由变化时做一些额外的逻辑处理就可以实现动态设置页面标题。首先,我们定义一个基本的路由:

  1. const routes: Routes = [{
  2. path: 'calendar',component: CalendarComponent,children: [
  3. { path: '',redirectTo: 'new',pathMatch: 'full' },{ path: 'all',component: CalendarListComponent },{ path: 'new',component: CalendarEventComponent },{ path: ':id',component: CalendarEventComponent }
  4. ]
  5. }];

在这里定义一个日历应用,他有一个路由/calendar, 还有三个子路由, /all对应日历列表页new对应新建日历,:id对应日历详情。现在,我们定义一个data对象然后设置一个title属性来作为每个页面标题

  1. const routes: Routes = [{
  2. path: 'calendar',component: CalendarListComponent,data: { title: 'My Calendar' } },component: CalendarEventComponent,data: { title: 'New Calendar Entry' } },data: { title: 'Calendar Entry' } }
  3. ]
  4. }];

好了,路由定义完了,现在我们看下如何监听路由变化

Routing events

Angular路由配置非常简单,但是路由通过Observables使用起来也非常强大。
我们可以在根组件中全局监听路由的变化:

  1. ngOnInit() {
  2. this.router.events
  3. .subscribe((event) => {
  4. // example: NavigationStart,RoutesRecognized,NavigationEnd
  5. console.log(event);
  6. });
  7. }

我们要做的就是在导航结束时获取到定义的数据然后设置页面标题,可以检查 NavigationStart,RoutesRecognized,NavigationEnd 哪种事件是我们需要的方式,理想情况下NavigationEnd,我们可以这么做:

  1. this.router.events
  2. .subscribe((event) => {
  3. if (event instanceof NavigationEnd) { // 当导航成功结束时执行
  4. console.log('NavigationEnd:',event);
  5. }
  6. });

这样我们就可以在导航成功结束时做一些逻辑了,因为Angular路由器是reactive响应式的,所以我们可以使用 RxJS 实现更多的逻辑,我们来导入以下操作符:

  1. import 'rxjs/add/operator/filter';
  2. import 'rxjs/add/operator/map';
  3. import 'rxjs/add/operator/mergeMap';

现在我们已经添加filtermapmergeMap 三个操作符,我们可以过滤出导航结束的事件:

  1. this.router.events
  2. .filter(event => event instanceof NavigationEnd)
  3. .subscribe((event) => {
  4. console.log('NavigationEnd:',event);
  5. });

其次,因为我们已经注入了Router类,我们可以使用 routerState获取路由状态树得到最后一个导航成功的路由:

  1. this.router.events
  2. .filter(event => event instanceof NavigationEnd)
  3. .map(() => this.router.routerState.root)
  4. .subscribe((event) => {
  5. console.log('NavigationEnd:',event);
  6. });

然而,一个更好的方式就是使用 ActivatedRoute 来代替 routerState.root,我们可以将其ActivatedRoute注入类中:

  1. import { Router,NavigationEnd,ActivatedRoute } from '@angular/router';
  2.  
  3. @Component({...})
  4. export class AppComponent implements OnInit {
  5. constructor(
  6. private router: Router,private activatedRoute: ActivatedRoute,private titleService: Title
  7. ) {}
  8. ngOnInit() {
  9. // our code is in here
  10. }
  11. }

注入之后我们再来优化下:

  1. this.router.events
  2. .filter(event => event instanceof NavigationEnd)
  3. .map(() => this.activatedRoute)
  4. .subscribe((event) => {
  5. console.log('NavigationEnd:',event);
  6. });

我们使用 map 转换了我们观察到的内容,返回一个新的对象 this.activatedRoutestream 流中继续执行。 我们使用 filter(过滤出导航成功结束)map(返回我们的路由状态树) 成功地返回我们想要的事件类型 NavigationEnd

接下来是最有意思的部分,我们将创建一个while循环遍历状态树得到最后激活的 route,然后将其作为结果返回到流中:

  1. this.router.events
  2. .filter(event => event instanceof NavigationEnd)
  3. .map(() => this.activatedRoute)
  4. .map(route => {
  5. while (route.firstChild) route = route.firstChild;
  6. return route;
  7. })
  8. .subscribe((event) => {
  9. console.log('NavigationEnd:',event);
  10. });

接下来我们可以通过路由配置的属性获取相应的页面标题。然后,我们还需要另外两个运算符:

  1. this.router.events
  2. .filter(event => event instanceof NavigationEnd)
  3. .map(() => this.activatedRoute)
  4. .map(route => {
  5. while (route.firstChild) route = route.firstChild;
  6. return route;
  7. })
  8. .filter(route => route.outlet === 'primary') // 过滤出未命名的outlet,<router-outlet>
  9. .mergeMap(route => route.data) // 获取路由配置数据
  10. .subscribe((event) => {
  11. console.log('NavigationEnd:',event);
  12. });

现在我们 titleService 只需要实现:

  1. .subscribe((event) => this.titleService.setTitle(event['title']));

下面看一下最终代码

  1. import 'rxjs/add/operator/filter';
  2. import 'rxjs/add/operator/map';
  3. import 'rxjs/add/operator/mergeMap';
  4.  
  5. import { Component,OnInit } from '@angular/core';
  6. import { Router,ActivatedRoute } from '@angular/router';
  7. import { Title } from '@angular/platform-browser';
  8.  
  9. @Component({...})
  10. export class AppComponent implements OnInit {
  11. constructor(
  12. private router: Router,private titleService: Title
  13. ) {}
  14. ngOnInit() {
  15. this.router.events
  16. .filter(event => event instanceof NavigationEnd)
  17. .map(() => this.activatedRoute)
  18. .map(route => {
  19. while (route.firstChild) route = route.firstChild;
  20. return route;
  21. })
  22. .filter(route => route.outlet === 'primary')
  23. .mergeMap(route => route.data)
  24. .subscribe((event) => this.titleService.setTitle(event['title']));
  25. }
  26. }

本文翻译自dynamic-page-titles-angular-2-router-events,本人水平有限,如果有翻译不好的地方欢迎大家联系我

猜你在找的Angularjs相关文章