【发布时间】:2016-07-05 03:44:59
【问题描述】:
我正在努力在 angularjs2 中自动生成 jsonld 脚本,但是,我找到了 angularjs1 的解决方案。 有没有人可以解决这个问题。
【问题讨论】:
-
您好,感谢您的回复,但此解决方案适用于 angularjs1 而不是完全不同的版本 2。
-
找到什么了吗?
我正在努力在 angularjs2 中自动生成 jsonld 脚本,但是,我找到了 angularjs1 的解决方案。 有没有人可以解决这个问题。
【问题讨论】:
不使用管道的解决方案(有点干净的方式)
使用提供的 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);
}
【讨论】:
我发现使用“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 中测试了这段代码的输出,它的工作方式与预期一样。
【讨论】: