【发布时间】:2018-06-28 01:42:16
【问题描述】:
我正在使用 Angular 5 构建一个小型宣传册类型的网站。到目前为止,我已经设置好了路线,并且页面标题会根据激活的路线动态变化。我使用此博客上的说明完成了这项工作:https://toddmotto.com/dynamic-page-titles-angular-2-router-events
我目前将我的路线和标题存储在 app.module.ts 中:
imports: [
BrowserModule,
RouterModule.forRoot([
{
path: '',
component: HomeComponent,
data: {
title: 'Home'
}
},
{
path: 'about',
component: AboutComponent,
data: {
title: 'About'
}
},
{
path: 'products-and-services',
component: ProductsServicesComponent,
data: {
title: 'Products & Services'
}
},
{
path: 'world-class-laundry',
component: LaundryComponent,
data: {
title: 'World Class Laundry'
}
},
{
path: 'contact',
component: ContactComponent,
data: {
title: 'Contact'
}
},
{
path: '**',
component: NotFoundComponent,
data: {
title: 'Page Not Found'
}
}
])
],
如果在data: 下添加它们很容易的话,我也想将我的元描述存储在那里。
我正在使用以下代码提取该标题数据,这在上面的博客链接中有所说明:
ngOnInit() {
this.router.events
.filter((event) => event instanceof NavigationEnd)
.map(() => this.activatedRoute)
.map((route) => {
while (route.firstChild) route = route.firstChild;
return route;
})
.filter((route) => route.outlet === 'primary')
.mergeMap((route) => route.data)
.subscribe((event) => {
this.titleService.setTitle(event['title']);
});
}
所以我的问题是,有没有办法使用相同的方法动态设置元描述?如果有办法结合页面标题和元描述功能,那将是理想的。
我的 Angular 培训非常有限,所以这可能是个小问题。我更像是一个设计师/css/html 类型的人。
【问题讨论】:
-
从 Angular 4 开始,已经有一个内置服务可以从 '@angular/platform-browser' 导入 { Meta };看这里angular.io/api/platform-browser/Meta
-
@elasticrash 是的,我研究了 Meta。我更感兴趣的是如何将 Meta 应用到我已经拥有的东西中。
-
元描述在哪里?
-
@Melchia 如果可能的话,我想存储我的元描述,页面标题是 app.module.ts。
-
你不能只在数据中添加一个属性描述并做你在 ngOnInit 中做的同样的事情吗?
标签: angular typescript angular-ui-router