问题描述
我的问题与 this 类似,但我没有收到任何错误。 我添加的标题在选项卡上可见,当我检查页面时可以看到元标记。但是在视图页面源上,标题和元标记都不可见。如何让它们在查看页面源代码中也可见?
我已经预渲染了我的网站。
我正在使用的代码:
import { Component,OnInit } from '@angular/core';
import { Meta,Title } from '@angular/platform-browser';
import { Router } from '@angular/router';
@Component({
selector: 'app-some',templateUrl: './some.component.html',styleUrls: ['./some.component.css'],})
export class HighlightsComponent implements OnInit {
constructor(
private router: Router,private titleService: Title,private MetaService: Meta
) {}
title = 'Some Title';
ngOnInit(): void {
this.titleService.setTitle(this.title);
this.MetaService.addTags([
{ name: 'robots',content: 'index,follow' },]);
}
}
解决方法
导入元服务
在使用元服务之前,我们需要从平台浏览器包中导入它。
import { Meta } from '@angular/platform-browser';
接下来,我们将通过构造函数将其注入到我们的组件中。
构造函数(私有元:元){}
添加元标签
为了添加新的元标记,Angular Meta 服务提供了两个方法 addTag 和
addTags.
this.meta.addTag({ name: 'description',content: 'This is an article about Angular Meta service' });
The addTag method accepts a meta definition object as a parameter that is used to describe the meta tag.
以上代码将生成以下 HTML 元标记元素。
您还可以使用 addTags 同时添加多个元标记。
this.meta.addTags([
{ name: 'description',content: 'This is an article about Angular Meta service' },{ name: 'keywords',content: 'angular,javascript,typescript,meta,seo' }
]);
以上代码将生成以下 HTML 元标记元素:
要记住的一件事是 addTag 和 addTags 方法也接受第二个参数 forceCreation,这会强制方法创建一个新的元标记元素,而不检查它是否已经存在。
检索元标记
要从 DOM 中读取元标记,我们可以使用 Meta 服务提供的 getTag 或 getTags 方法。 getTag 和 getTags 方法接受一个表示属性选择器的字符串,并根据该字符串返回匹配的元素
string:
const keywords = this.meta.getTag('name=keywords');
console.log(keywords.content);
// Output: angular,seo
The getTag method returns an HTMLMetaElement while getTags returns array of HTMLMetaElements.
要记住的一件事是 getTag 返回选择器参数中描述的匹配元标记的第一个实例,而 getTags 方法返回与选择器匹配的元标记的所有实例。
let tags = this.meta.getTags('name');
在上面的代码中,getTags 将返回包含 name 属性的元标记的所有实例,并将这些实例以数组的形式保存在 tags 变量中。
更新元标记
要更新现有的元标记,我们可以使用与 Angular Meta 服务捆绑在一起的 updateTag 方法。
this.meta.addTag({ name: 'keywords',seo' });
setTimeout(() => {
this.meta.updateTag(
{ name: 'keywords',meta' },'name=keywords'
)
},4000)
在上面的代码片段中,我们首先添加了一个带有名称关键字的新元标记。接下来,我们将在 4 秒后使用 updateTag 方法更新标签。要记住的一件事是,如果 DOM 中不存在带有 name 关键字的标签,则 updateTag 方法将创建一个新元素。