javascript - 在 Angular2 组件模板中添加 ld+json 脚本标签

标签 javascript angular seo

我试过太多坑爹的方法, 例如 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/

相关文章:

javascript - 使用 Javascript 下划线删除重复对象

angular - TypeScript -'s Angular Framework Error - "没有将 exportAs 设置为 ngForm 的指令”

Angular 2+等待方法/可观察完成

ruby-on-rails - Rails - 从文本 block 中提取 seo 关键字

Angular 无法加载其他路线

javascript - 限制输入到文本框: it only accept number and should not accept decimal value

javascript - 如何在angularjs中逐行折叠

javascript - 是否有一种搜索算法可以一直搜索有序列表,直到所有值都相等?

Angular Form Array 访问静态数据

php - 我在我的服务器上发现了这个奇怪的 PHP 文件,它似乎破坏了我们网站的 SEO。有人知道它有什么作用吗?