首页 > 解决方案 > 使用基类在 Angular 7 中设置页面标题

问题描述

在我的 Angular 7 应用程序中,我想要一个可以扩展所有路由/页面组件的基类,以允许我以一致的方式设置页面标题。现在我不确定我想做的事情是否可能。这是我到目前为止所拥有的:

import { Injector } from '@angular/core';
import { PageTitleService } from '../services/page-title/page-title.service';

export abstract class BaseTitledPage {
    /**
     * This string is used to set the page title in the browser window/tab.
     * It is also generally encouraged to be used as the "title" of the page is the UI so that these titles are always in sync
     */
    protected pageTitle: string;

    protected constructor(injectedPageTitle: string) {
        this.pageTitle = injectedPageTitle;

        const injector = Injector.create({
            providers: [ {provide: PageTitleService, deps: []} ]
        });

        const pageTitleService = injector.get(PageTitleService);

        this.setPageTitle(pageTitleService, this.pageTitle);
    }

    private setPageTitle(svc: PageTitleService, title: string): void {
        svc.setPageTitle(title);
    }
}

然后一个页面会像这样使用它:

@Component({
    selector: 'app-page-home',
    templateUrl: './page-home.component.html'
})
export class PageHomeComponent extends BaseTitledPage {
    constructor() {
        super('Home');
    }
}

理想情况下,我可以{{pageTitle}}在我的模板中使用,这将匹配浏览器选项卡/窗口中的实际页面标题。


我想在这里做的可能吗?我可以像这样在非组件基类中获取或注入服务吗?我知道可以在任何子类上提供该服务并将其传递给super('Home, pageTitleService)但我想避免这种情况,如果我可以让事情变得更简单。

标签: angulartypescriptextendssubclassing

解决方案


推荐阅读