Angular中TitleService扩展实现及调用问题
扩展Angular TitleService的问题解决
问题1:子类构造函数的super参数处理
Angular的Title服务构造函数需要的_doc参数,本质是浏览器的document对象,可通过Angular提供的DOCUMENT令牌注入,无需传null。修改后的服务代码如下:
import { Injectable, Inject } from '@angular/core'; import { Title } from '@angular/platform-browser'; import { DOCUMENT } from '@angular/common'; import { OtherService } from './your-other-service-path'; @Injectable({ providedIn: 'root' }) export class PageTitleService extends Title { constructor( @Inject(DOCUMENT) private document: Document, public myOtherService: OtherService ) { // 将注入的document传给父类构造函数 super(document); } public setPageTitle(customLabel: string) { const title = this.myOtherService.getPageTitlebyLabel(customLabel); this.setTitle(title); } }
传入合法的document对象后,父类的setTitle方法就能正常操作页面标题,不会因null参数导致异常。
问题2:消费组件调用方法的正确方式
- 确保
PageTitleService被Angular依赖注入系统管理:添加@Injectable({ providedIn: 'root' })实现全局注册,或者在模块的providers数组中声明。 - 在需要调用的组件中注入
PageTitleService,直接调用setPageTitle方法即可,无需传递组件引用:
import { Component, OnInit } from '@angular/core'; import { PageTitleService } from './your-page-title-service-path'; @Component({ selector: 'app-home', templateUrl: './home.component.html' }) export class HomeComponent implements OnInit { constructor(private pageTitleService: PageTitleService) {} ngOnInit() { this.pageTitleService.setPageTitle('Home_Label'); } }
Title服务本身就是操作全局页面标题的,你的扩展服务已经封装了从OtherService获取标题并设置的逻辑,组件只需传入对应标签即可完成标题设置,不需要额外传递组件引用。
内容的提问来源于stack exchange,提问作者hillcountry99
相关产品推荐
相关产品推荐

