最近在用Angular8.1.0寫個(gè)微信公眾號(hào)的項(xiàng)目架構(gòu)官扣,由于angular是單頁面框架祝蝠,并無頁面之分,所以想實(shí)現(xiàn)切換頁面title绣张,并不能直接html設(shè)置答渔,但別擔(dān)心,angular有專門的模塊可以處理侥涵,如下:
import { Title } from '@angular/platform-browser';
ts具體用法:
constructor(private titleService: Title) { }
this.titleService.setTitle(`頁面title`);
這樣就能設(shè)定每個(gè)頁面的title啦研儒,是不是很簡(jiǎn)單 :)
但是,在每個(gè)頁面都寫一次是不是很繁瑣呢独令,也不利于管理標(biāo)題端朵。是否有一種更簡(jiǎn)單的設(shè)定方法呢,如果只在業(yè)務(wù)代碼中寫一次燃箭,是不是就很友好了冲呢!
所以,可以將設(shè)定頁面title封裝成一個(gè)公共方法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: '個(gè)人中心' } },
{
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è)置好了標(biāo)題,但是如果讓設(shè)置的title起效果呢累榜,就要看下一步了
2营勤、創(chuàng)建一個(gè)公共服務(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è)置頁面標(biāo)題
}
運(yùn)行代碼寿羞,大功告成!