我刚刚创建了ng2-meta,这是一个 Angular2 模块,可以根据当前路由更改元标记。
const routes: Routes = [
{
path: 'home',
component: HomeComponent,
data: {
meta: {
title: 'Home page',
description: 'Description of the home page'
}
}
},
{
path: 'dashboard',
component: DashboardComponent,
data: {
meta: {
title: 'Dashboard',
description: 'Description of the dashboard page',
'og:image': 'http://example.com/dashboard-image.png'
}
}
}
];
您也可以从组件、服务等更新元标记。
class ProductComponent {
...
constructor(private metaService: MetaService) {}
ngOnInit() {
this.product = //HTTP GET for product in catalogue
metaService.setTitle('Product page for '+this.product.name);
metaService.setTag('og:image',this.product.imageURL);
}
}
虽然这迎合了启用 Javascript 的爬虫(如 Google),但您可以为非 Javascript 爬虫(如 Facebook 和 Twitter)设置后备元标记。
<head>
<meta name="title" content="Website Name">
<meta name="og:title" content="Website Name">
<meta name="og:image" content="http://example.com/fallback-image.png">
...
</head>
对服务器端渲染的支持正在进行中。