Service 简介
Angular Service 用于获取和设置当前 HTML 文档的标题。 Service 提供了以下方法:
首先要使用 服务,我们需要从 @angular/platform-browser 库导入 类,然后利用 Angular 依赖注入的机制,通过构造注入的方式注入 服务:
import { Component, OnInit } from "@angular/core";
import { } from "@angular/platform-browser";
@Component({
selector: "app-root",
template: `
<h3>Angular Service</h3>
`
})
export class AppComponent {
constructor(public : ) {}
}set ()
该方法用于设置当前 HTML 文档的标题,它接收一个参数:
- new :标题文本
set () {
this. .set ("前端修仙之路");
}get ()
该方法用于获取当前 HTML 文档的标题:
get () {
console.log(this. .get ());
}Service API 很简单,以下是完整的示例:
import { Component, OnInit } from "@angular/core";
import { } from "@angular/platform-browser";
@Component({
selector: "app-root",
template: `
<h3>Angular Service</h3>
<button (click)="set ()">Set Page </button>
<button (click)="get ()">Get Page </button>
`
})
export class AppComponent {
constructor(public : ) {}
set () {
this. .set ("前端修仙之路");
}
get () {
console.log(this. .get ());
}
}Service 实战
在 SPA 单页应用的开发过程中,经常需要根据不同的路由显示不同的标题,即动态地设置页面的标题。针对这种需求,我们可以通过订阅路由事件,然后在页面导航成功后,利用 服务动态设置页面的标题或 信息。
this.router.events.subscribe((event: any) => {
if (event instanceof NavigationEnd) {
switch (event.urlAfterRedirects) {
case '/':
this. .updateTag({
name: 'de ion',
content: 'Angular Example app with Angular CLI, Angular Material and more'
});
break;
case '/' + AppConfig.routes.heroes: // routes: { heroes: 'heroes' },
this. .set ('Heroes list');
this. .updateTag({
name: 'de ion',
content: 'List of super-heroes'
});
break;
}
}
});示例来源于 —— angular6-example-app ,该示例主要介绍了如何利用路由事件来动态设置页面的标题。而实际的开发过程中,我们会在定义路由时,为需要设置标题的路由,定义一个 data 属性,然后设置该属性对应的属性值为一个包含 属性的对象,比如:
const routes: Routes = [
{
path: '',
component: HomeComponent,
data: { : "My Home Page" },
},
{
path: 'detail/:id',
component: DetailComponent,
}
];之后,我们只要在激活当前页面的时候,获取对应的路由配置,就可以利用 服务来改变当前页面的标题。此外在实际的开发中,可能会遇到一些复杂的场景,比如子路由、多层嵌套路由等。针对这种情形,建议有需要的同学认真阅读一下 Todd Motto 大神 dynamic-page- s-angular-2-router-events 这篇文章,虽然使用的是 Angular 2.x 版本,但核心的思想是一致的,大家只需根据当前使用的 Angular 版本进行相应的代码更新。
Service 源码简析
类及构造函数
@Injectable({providedIn: 'root', useFactory: create , deps: []})
export class {
constructor(@Inject(DOCUMENT) private _doc: any) {}
}通过观察 Injectable 装饰器的 元信息,我们知道 服务将被注册在根级注入器中,当首次获取 服务时,将使用 create () 工厂方法创建对应的实例。
import {Inject, Injectable, inject} from '@angular/core';
export function create () {
return new (inject(DOCUMENT));
}set ()
set (new : string) {
getDOM().set (this._doc, new );
}以上代码通过调用 getDOM() 方法获取 DomAdapter 对象,然后调用该对象的 set () 方法设置当前页面的标题。
get ()
get (): string {
return getDOM().get (this._doc);
}参考资源
继续阅读与本文标签相同的文章
Angular 工具篇之Storybook
企业级分布式应用服务EDAS评测报告
-
Angular 自定义属性指令
2026-05-21栏目: 教程
-
Angular 工具篇之分析包的大小
2026-05-21栏目: 教程
-
Angular Multi Providers 和 APP_INITIALIZER
2026-05-21栏目: 教程
-
RxDB 异常机制
2026-05-21栏目: 教程
-
Angular 工具篇之国际化处理
2026-05-21栏目: 教程
