Angular8 設(shè)定頁面標題title

最近在用Angular8.1.0寫個微信公眾號的項目架構(gòu),由于angular是單頁面框架,并無頁面之分,所以想實現(xiàn)切換頁面title,并不能直接html設(shè)置,但別擔心,angular有專門的模塊可以處理,如下:

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

ts具體用法:

 constructor(private titleService: Title) { }

 this.titleService.setTitle(`頁面title`);

這樣就能設(shè)定每個頁面的title啦,是不是很簡單 :)

但是,在每個頁面都寫一次是不是很繁瑣呢,也不利于管理標題。是否有一種更簡單的設(shè)定方法呢,如果只在業(yè)務(wù)代碼中寫一次,是不是就很友好了!
所以,可以將設(shè)定頁面title封裝成一個公共方法setTitle

在官網(wǎng)angular路由中向我們介紹了路由上data屬性,為管理頁面title提供了便利。

1、先配置頁面的路由文件,設(shè)置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: '自助預(yù)約' }
  },
  // { path: 'confirmOrder', loadChildren: './confirm-order/confirm-order.module#ConfirmOrderPageModule' }
];

已經(jīng)設(shè)置好了標題,但是如果讓設(shè)置的title起效果呢,就要看下一步了

2、創(chuàng)建一個公共服務(wù)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中調(diào)用

引用注入公共服務(wù)CommonService

import { CommonService } from './services/common.service';
constructor(private common: CommonService) { }

ngOnInit() {
  this.common.setTitle();   //設(shè)置頁面標題
}

運行代碼,大功告成!

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容