我尝试过太多棘手的方法, 例如Renderer2或ɵDomAdapter, 脚本标签很好地集成在html中, 但是当使用谷歌的结构化数据工具加载网址时, ld + json脚本没有渲染!
加载组件后,有没有办法让谷歌渲染页面?
答案 0 :(得分:2)
有几种方法可以实现这一目标。下面的代码是我提出的最佳解决方案。此示例也适用于Angular Universal。
import { Component, OnInit } from '@angular/core';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
@Component({
selector: 'app-root',
template: '<div [innerHTML]="jsonLD"></div>'
})
export class JsonLdComponent implements OnChanges {
jsonLD: SafeHtml;
constructor(private sanitizer: DomSanitizer) { }
ngOnInit(changes: SimpleChanges) {
const json = {
"@context": "http://schema.org",
"@type": "Organization",
"url": "https://google.com",
"name": "Google",
"contactPoint": {
"@type": "ContactPoint",
"telephone": "+1-000-000-0000",
"contactType": "Customer service"
}
};
// Basically telling Angular this content is safe to directly inject into the dom with no sanitization
this.jsonLD = this.getSafeHTML(json);
}
getSafeHTML(value: {}) {
const json = JSON.stringify(value, null, 2);
const html = `${json}`;
// Inject to inner html without Angular stripping out content
return this.sanitizer.bypassSecurityTrustHtml(html);
}
}
我在这篇博文中详细介绍https://coryrylan.com/blog/angular-seo-with-schema-and-json-ld
我也采用了这种技术并将其包装成npm包 它更可重复使用。 https://github.com/coryrylan/ngx-json-ld
答案 1 :(得分:2)
我在Angular 9 TypeScript中使用了此变体
import { Component, OnInit } from '@angular/core';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
@Component({
selector: 'app-schema-org',
template: '<div [innerHTML]="jsonLD"></div>',
})
export class SchemaOrgComponent implements OnInit {
jsonLD: SafeHtml;
constructor(private sanitizer: DomSanitizer) { }
ngOnInit() {
const json = {
'@context': 'http://schema.org',
'@type': 'Organization',
'url': 'https://google.com',
'name': 'Google',
'contactPoint': {
'@type': 'ContactPoint',
'telephone': '+1-000-000-0000',
'contactType': 'Customer service',
},
};
// Basically telling Angular this content is safe to directly inject into the dom with no sanitization
this.jsonLD = this.getSafeHTML(json);
}
getSafeHTML(value: {}) {
const json = JSON.stringify(value, null, 2);
const html = `<script type="application/ld+json">${json}</script>`;
// Inject to inner html without Angular stripping out content
return this.sanitizer.bypassSecurityTrustHtml(html);
}
}
然后将其命名为<app-schema-org></app-schema-org>
对我来说,上面的示例(https://stackoverflow.com/a/47299603/5155484)没有意义,因为它导入OnInit并实现OnChange并使用带有参数的ngOnInit进行更改。
这是我的固定示例。