2016-07-05 25 views
5

我正在努力自动生成angularjs2中的jsonld脚本,但是,我找到了angularjs1的解决方案。 有没有人有这方面的解决方案。json-ld脚本标记为angularjs2

+0

访问'http://stackoverflow.com/questions/35332430/angularjs-script-tag-json-ld/35333500#35333500' – AK1

+0

嗨,感谢您的回复,但这个解决方案是为angularjs1不是版本2,这是完全不同的。 –

+0

发现了什么? – Nicky

回答

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中测试了此代码的输出,它的工作方式与预期相同。

+0

我有同样的问题。你能解释一下如何解决这个问题吗?请检查此链接https://stackoverflow.com/questions/44389546/schema-not-detected-in-google-structured-data-testing-tool – vel

+0

@vel,您需要预先在Web服务器上使用Angular通用,以便Google结构化数据测试工具能够解析包含结构化数据的HTML代码。参见示例[starter project](https://github.com/robwormald/ng-universal-demo)。 – tooleks

+0

我尝试了角度通用。但我不能使用使用Ng build --prod。那就是问题所在。如何解决这个问题? – vel

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); 
     }