2016-07-05 3 views
5

私はangularjs2でjsonldスクリプトを自動生成するのに苦労していますが、私はangularjs1の解決策を見つけました。 誰にでもこれに対する解決策がありますか?Json-ldスクリプトタグfor angularjs2

+0

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

+0

ご返信ありがとうございますが、このソリューションはangularjs1用であり、バージョン2では完全に異なります。 –

+0

まだ何も見つかりませんでしたか? – Nicky

答えて

2

私は少し「醜い」ではなく「safeHtml」パイプを使用して作業溶液が見つかりました:

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

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と連携して、それを使用することで、任意のスクリプトコードを挿入することができます

私はこのコードの出力をGoogle Structured Data Testing Toolでテストしましたが、期待どおりに動作します。

+0

私は同じ問題があります。この問題を解決する方法を教えてください。このリンクを確認してくださいhttps://stackoverflow.com/questions/44389546/schema-not-detected-in-google-structured-data-testing-tool – vel

+0

@vel、角度を使用してWebサーバー上で角度アプリケーションを事前レンダリングする必要がありますユニバーサルは、Googleの構造化データテストツールが構造化データを含むHTMLコードを解析できるようにするためです。サンプル[starter project](https://github.com/robwormald/ng-universal-demo)を参照してください。 – tooleks

+0

私は角度ユニバーサルで試しました。しかし、私はNg build --prodを使うことはできません。それが問題です。これを解決するには? – vel

1
(多少クリーン方法)

使用コンポーネントでテンプレート

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

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

ソリューション/ディレクティブ

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