【问题标题】:Json-ld script tag for angularjs2angularjs2 的 Json-ld 脚本标签
【发布时间】:2016-07-05 03:44:59
【问题描述】:

我正在努力在 angularjs2 中自动生成 jsonld 脚本,但是,我找到了 angularjs1 的解决方案。 有没有人可以解决这个问题。

【问题讨论】:

标签: angular json-ld


【解决方案1】:

不使用管道的解决方案(有点干净的方式)

使用提供的 this.sanitizer.bypassSecurityTrustHtml https://angular.io/guide/security#sanitization-and-security-contexts

在模板中

<div [innerHtml]="jsonLDString"></div>

在组件/指令中

  private jsonld: any;
  public jsonLDString: any;

   private setJsonldData() {
        this.jsonld = {
          '@context': 'http://schema.org/',
          '@type': 'Service',
          'name': this.providerName,
          'description': this.providerDescription,
          'aggregateRating': {
            '@type': 'AggregateRating',
            'ratingValue': '3',
            'bestRating': '5',
            'ratingCount': '3'
          },
          'url' : this.providerUrl
        };
        this.jsonLDString = '<script type="application/ld+json">' + JSON.stringify(this.jsonld) + '</script>';
        this.jsonLDString  = this.sanitizer.bypassSecurityTrustHtml(this.jsonLDString);
      }

【讨论】:

    【解决方案2】:

    我发现使用“safeHtml”管道的解决方案有点“丑陋”但可行:

    import {Pipe, PipeTransform} from '@angular/core';
    import {DomSanitizer, SafeHtml} from '@angular/platform-browser';
    
    @Pipe({name: 'safeHtml'})
    export class SafeHtmlPipe implements PipeTransform {
        constructor(protected sanitized:DomSanitizer) {
        }
    
        transform(value:any):SafeHtml {
            return this.sanitized.bypassSecurityTrustHtml(value);
        }
    }
    

    通过与Angular Universal 一起使用,您可以插入任何脚本代码:

    <div [innerHtml]="'<script type=\'application/ld+json\'>' + jsonLdStringifiedObj + '</script>' | safeHtml"></div>
    

    我已经在Google Structured Data Testing Tool 中测试了这段代码的输出,它的工作方式与预期一样。

    【讨论】:

    • 我有同样的问题。你能解释一下如何解决这个问题吗?请查看此链接stackoverflow.com/questions/44389546/…
    • @vel,您需要使用 Angular Universal 在网络服务器上预渲染您的 Angular 应用程序,以便 Google 结构化数据测试工具能够解析包含您的结构化数据的 HTML 代码。请参阅示例starter project
    • 我尝试使用 Angular Universal。但我不能使用使用 Ng build --prod。那就是问题所在。如何解决?
    • @vel,为什么你不能使用它?能否提供错误日志?
    • 在不使用管道的情况下添加了微笑示例
    猜你喜欢
    • 2016-05-21
    • 2021-10-15
    • 2018-03-30
    • 1970-01-01
    • 2018-02-03
    • 2022-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多