美文网首页
Angular8 设定页面标题title

Angular8 设定页面标题title

作者: Steven2619 | 来源:发表于2019-08-08 14:58 被阅读0次

    最近在用Angular8.1.0写个微信公众号的项目架构,由于angular是单页面框架,并无页面之分,所以想实现切换页面title,并不能直接html设置,但别担心,angular有专门的模块可以处理,如下:

    import { Title } from '@angular/platform-browser';
    

    ts具体用法:

     constructor(private titleService: Title) { }
    
     this.titleService.setTitle(`页面title`);
    

    这样就能设定每个页面的title啦,是不是很简单 :)

    但是,在每个页面都写一次是不是很繁琐呢,也不利于管理标题。是否有一种更简单的设定方法呢,如果只在业务代码中写一次,是不是就很友好了!
    所以,可以将设定页面title封装成一个公共方法setTitle

    在官网angular路由中向我们介绍了路由上data属性,为管理页面title提供了便利。

    1、先配置页面的路由文件,设置data属性中的title

    const routes: Routes = [
      { path: '', redirectTo: 'home', pathMatch: 'full' },
      { path: 'home', component: HomeComponent, data: { title: '主页' } },
      { path: 'personalCenter', component: PersonalCenterComponent, 
        data: { title: '个人中心' } },
      {
        path: 'bindCard',component:  BindingCardComponent,
        data: { title: '绑定就诊卡' }
      },
      {
        path: 'hasCard', loadChildren: () => import(`./pages/has-card/has-card.module`).then(m => m.HasCardModule),
      },
      {
        path: 'reservation', loadChildren: () => import(`./pages/reservation/reservation.module`).then(m => m.ReservationModule),
        data: { title: '自助预约' }
      },
      // { path: 'confirmOrder', loadChildren: './confirm-order/confirm-order.module#ConfirmOrderPageModule' }
    ];
    
    

    已经设置好了标题,但是如果让设置的title起效果呢,就要看下一步了

    2、创建一个公共服务CommonService

    import { Injectable } from '@angular/core';
    import { Router, NavigationEnd, ActivatedRoute } from '@angular/router';
    import { Title } from '@angular/platform-browser';
    import { map, filter } from "rxjs/operators";
    
    @Injectable({
      providedIn: 'root'
    })
    export class CommonService {
    
      constructor(private router: Router,
        private activatedRoute: ActivatedRoute,
        private titleService: Title) {
    
      }
    
      public setTitle() {
        this.router.events
          .pipe(
            filter(event => event instanceof NavigationEnd),
            map(() => this.router)
          )
          .subscribe((event) => {
            const titles = this.getTitle(this.router.routerState, this.router.routerState.root);
            const title = titles[titles.length - 1];
            // console.log(title);
            if (title) {
              this.titleService.setTitle(title);
            }
          });
      }
    
      public getTitle(state, parent) {
        const data = [];
        if (parent && parent.snapshot.data && parent.snapshot.data.title) {
          data.push(parent.snapshot.data.title);
        }
        if (state && parent) {
          data.push(...this.getTitle(state, state.firstChild(parent)));
        }
        return data;
      }
    }
    

    至此,核心方法封装好了,下一步就该用起来

    3、在根模块app.component.ts中调用

    引用注入公共服务CommonService

    import { CommonService } from './services/common.service';
    constructor(private common: CommonService) { }
    
    ngOnInit() {
      this.common.setTitle();   //设置页面标题
    }
    

    运行代码,大功告成!

    相关文章

      网友评论

          本文标题:Angular8 设定页面标题title

          本文链接:https://www.haomeiwen.com/subject/zohxjctx.html