2016-07-05 9 views
5

Próbuję automatycznie wygenerować skrypt jsonld w angularjs2, jednak znalazłem rozwiązanie dla angularjs1. Czy ktoś ma rozwiązanie tego problemu.Znacznik skryptu Json-ld dla angularjs2

+0

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

+0

Dziękuję za odpowiedź, ale to rozwiązanie jest dla angularjs1 nie dla wersji 2, która jest zupełnie inna . –

+0

znalazłeś coś jeszcze? – Nicky

Odpowiedz

2

znalazłem trochę „brzydki”, ale rozwiązanie jest wykonywana przy użyciu „safeHtml” rura:

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

Używając go w parze z Angular Universal można wstawić dowolny kod skryptu:

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

Przetestowałem wyjście tego kodu w Google Structured Data Testing Tool i działa tak, jak oczekiwano.

+0

Mam ten sam problem. czy mógłbyś wyjaśnić, jak rozwiązać ten problem ?. Sprawdź ten link https://stackoverflow.com/questions/44389546/schema-not-detected-in-google-structured-data-testing-tool – vel

+0

@vel, musisz wstępnie zgłosić swoją aplikację kątową na serwerze internetowym za pomocą Angular Uniwersalne, aby narzędzie do testowania danych strukturalnych Google mogło analizować kod HTML, który zawiera dane strukturalne. Zobacz przykład [projekt początkowy] (https://github.com/robwormald/ng-universal-demo). – tooleks

+0

Próbowałem z uniwersalnym kątowym. Ale nie mogę użyć narzędzia Ng build --prod. To jest problem. Jak rozwiązać ten problem? – vel

1

Rozwiązanie bez użycia rury (nieco czysty sposób)

Użyj this.sanitizer.bypassSecurityTrustHtml warunkiem https://angular.io/guide/security#sanitization-and-security-contexts

W szablonie

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

W części/dyrektywa

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); 
     } 
Powiązane problemy