Angular 2/4 / Universal - How to use JSON-LD data?

I have a universal Angular 4 application and I want to start using microdata in JSON-LD format.

It uses a script tag with some content, for example:

 <script type="application/ld+json"> { "@context": "http://schema.org", ... } </script> 

Since this data needs to change for each view, I’m looking for a way to enter this data when changing the route in Angular 4. Currently, script tags are removed from the templates . When using a workaround with docuemnt.createElement this does not work on the Angular server-side generic application.

How can I do it?

EDIT

I am using Angular 4.xx, which is now called plain Angular . I insert document like this:

 import { DOCUMENT } from '@angular/platform-browser'; class Test { constructor(@Inject(DOCUMENT) private _document) { } public createScriptTag() { this._document.createElement('script'); // doesn't work server-side } } 
+5
source share
1 answer

EDIT: as stated in the comments, this solution is a hacker solution and should be used with caution.

You can enter some other types and functions of "ɵgetDOM" and "ɵDomAdapter" to get a link to dom. Sorry for calling it "some" service and function, because I don’t have a clue why they are called that. I just looked at the source code and how the angular command does this with MetaService.

 import { Inject } from '@angular/core'; import { Meta, Title } from '@angular/platform-browser'; import { ɵgetDOM, ɵDomAdapter, DOCUMENT } from '@angular/platform-browser'; @Injectable() export class SeoService { private dom: ɵDomAdapter; constructor(@Inject(DOCUMENT) private document: any, private titleService: Title, private metaService: Meta) { this.dom = ɵgetDOM(); let scriptEl = this.dom.createElement('script'); // .. } } 

I tested this and used it in production.

+1
source

Source: https://habr.com/ru/post/1266975/


All Articles