我试过太多坑爹的方法, 例如 Renderer2 或 ɵDomAdapter, 脚本标签很好地集成在 html 中, 但是当用谷歌的结构化数据工具加载 url 时, ld+json 脚本未呈现!
有没有办法让谷歌在加载组件后渲染页面?
最佳答案
我在 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 进行更改。
所以这是我的工作固定示例。
关于javascript - 在 Angular2 组件模板中添加 ld+json 脚本标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46815374/