angular - 使用基类在 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)
但我想避免这种情况,如果我可以让事情变得更简单。
解决方案
推荐阅读
- kubernetes - 如何检查 Web 服务的 SLA
- swift - 如何修复 Swift 5 中的 DispatchQueue 问题
- reporting-services - 导出到 Excel 时,SSRS 表达式不会格式化为数字
- ios - 如何从 NSManagedObject 属性派生核心数据属性键?
- python - 我想在我的数据框中创建一个新列,即每个特定行的犯罪率
- javascript - 由于 cors,将图像上传到 imgur 失败
- xamarin - 未找到具有以下 Xamarin.Android 功能的代理
- java - 随机将列表中的字符串逐个字符放入二维数组中
- html - 即使将 flex-shink 设置为 0,Flex 项目也会在宽度缩小时消失
- php - 在 WooCommerce 订单项中获取订单项 ID