如何在Angular4中添加动态元数据
我有一个需要动态元数据搜索引擎优化的angular4博客应用程序。 我的服务(BlogService)从PHP服务器提供JSON数据。 例如如何在Angular4中添加动态元数据
{"ID":"168","title":"HTML Src Test","description":"testing the html thingy in angular","content":"<h1>Hello, World ... This is a heading.<\/h1>\n<p><img title=\"test\" src=\"https:\/\/i.stack.imgur.com\/ipOIT.png\" alt=\"test\" width=\"20%\" \/><\/p>\n<pre class=\"prettyprint\">code code <br \/>function(){<br \/>console.log(\"hello\");<br \/>alert(\"hello\");<br \/>}<\/pre>\n<p> <\/p>","date":"26th Apr 2017","slug":"html-src-test","imagepath":"","category":"Testy Test McTest","ttr":1,"comcount":0}
这然后解释和显示的以通常的方式角(例如 {{post.title}})
BlogService:
getPost(slug: string): Promise<Post> {
const url = `${this.blogUrl}?id=${slug}`;
console.log(this.http.get(url).toPromise().then(response => response.json()));
return this.http.get(url)
.toPromise()
.then(response => response.json() as Post)
.catch(this.handleError);
}
BlogpostComponent:
ngOnInit(): void {
this.getData();
}
getData() {
this.route.params
.switchMap((params: Params) => this.service.getPost(params['slug']))
.subscribe(post => this.post = post);
}
如何从此HTTP请求传递数据并将其显示在HTML中的元标记中?
感谢
这是假设,我们意识到这意味着什么对SEO没有universal(服务器端渲染)等,并且还,我们使用的是V4 +。
您可以处理平台的浏览器,具有Title
和Meta
元等
import { Title, Meta, MetaDefinition } from '@angular/platform-browser';
...
constructor(
private _meta: Meta,
private _title: Title
...
this._title.setTitle('foo');
...
let meta: MetaDefinition[] = [
{ name: 'application-name', content: 'foo' },
{ name: 'description', content: 'bar' }
];
this._meta.addTags(meta);
更新: 所以,是的,你的情况,你可以添加一个基于响应。
.subscribe((post) => {
this.post = post;
this._title.setTitle(this.post.title);
});
对于清洁度我会创建一个单独的“service.method”喜欢“setPageMeta()”,其可以被用来处理route.data或HTTP响应。
感谢上述, 我如何将数据从组件传递到元数据? “this.post.title”是否工作(或类似)? –
我只是把相关的位,你会添加方法/事件(如路由器/ navigationEnd)或当一些数据返回。您将需要搜索控制台中的元素进行验证。 – Dylan
随着谷歌开始关注页面内的实际内容,而不是元标记标题和描述,元标记已经不再重要了(豁免必须)。只要确保页面中有良好的链接和内容,并确保您的网址不吸吮,并且可读。除此之外,安圭尔宇宙应该照顾其余的。 – EyoelD