首页 > 语言 > JavaScript > 正文

Angular 2 利用Router事件和Title实现动态页面标题的方法

2024-05-06 15:12:23
字体:
来源:转载
供稿:网友

Angular2 为我们提供了名为Title的Service用于修改和获取页面标题,但是如果只是能够在每个页面的ngOnInit方法中为每个页面设置标题岂不是太low了,不符合Angular2高(zhuang)大(bi)的身影。我们想要的结果是在页面改变时能够动态地改变页面标题,如此最好的解决方案就是组合使用Router事件和Title Service。

Title Service

使用Service自然首先要将其引入,不过要注意Title Service并不在@angular/core中,而是在@angular/platform-browser中:

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

引入之后,自然要将其注入到当前组件中,而这通常利用constructor完成:

import { Title } from '@angular/platform-browser';import {Component} from '@angular/core';@Component({})export class AppComponent {  constructor(private titleService: Title) {    // 使用this.title到处浪  }}

很显然,Title Service应该有某些操作页面标题的方法,不管通过查找文档还是查找源码我们都能很容易知道其只有两个方法:

getTitle() 用于获取当前当前页面的标题 setTitle(newTitle: String) 用于设置当前页面的标题

如果只是简单地静态地设置页面标题,则可以在ngOnInit方法中直接使用setTitle方法:

// import bala...@Component({})export class AppComponent implements OnInit {  constructor(private titleService: Title) {    // 使用this.title到处浪  }  ngOnInit() {    this.titleService.setTitle('New Title Here');  }}

在ngOnInit中使用setTitle方法设置文档标题是较好的时机,当然也可以根据自己的需求在任意地方使用setTitle方法。

Router和Router事件

使用Router和使用Title Service流程基本一致,先引入后注入,不过要注意Router和Title Service类似并不位于@angular/core中,而是位于@angular/router中:

import { Title } from '@angular/platform-browser';import {Component} from '@angular/core';import {Router} from '@angular/router';@Component({})export class AppComponent {  constructor(private titleService: Title, private router: Router) {    // 使用this.title和this.router到处浪  }}

Router配置

Angular2中通过URL、Router和Component之间的对应关系进行页面之间的跳转,Router把浏览器中的URL看做一个操作指南,据此可导航到一个由客户端生成的视图,并可以把参数传给支撑视图的相应组件。所以我们需要定义路由表:

// import bala...export const rootRouterConfig: Routes = [ { path: '', redirectTo: 'home', pathMatch: 'full'}, { path: 'home', component: HomeComponent, data: {title: 'Home-Liu'} }, { path: 'about', component: AboutComponent, data: {title: 'About-Liu'} }, { path: 'github', component: RepoBrowserComponent,  children: [   { path: '', component: RepoListComponent, data: {title: 'GitHub List'} },   { path: ':org', component: RepoListComponent,    children: [     { path: '', component: RepoDetailComponent, data: {title: 'Repo'} },     { path: ':repo', component: RepoDetailComponent, data: {title: 'RepoDetail'} }    ]   }] }, { path: 'contact', component: ContactComponent, data: {title: 'Contact-Liu'} }];             
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选