Search code examples
angularsingle-page-applicationldschema.org

Dynamically add ld+json schema in angular SPA index.html


I'm working on an angular app. Every page of my app is, basically, index.html:

<!doctype html>
<html lang="en">
<head>
    <base href="/my-app/">
    <title>MyApp</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link...>
    <script> ... </script>
</head>

<body>
    <app-root></app-root>
</body>
</html>

I want to add a schema.org's DataCatalog to this but with dynamic values. Imagine I've a list of items displayed, each item has a name, I want those names to appear in the DataCatalog's keywords (just imagine):

<!doctype html>
<html lang="en">
<head>
    <base href="/my-app/">
    <title>MyApp</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link...>
    <script> ... </script>
    <script type="application/ld+json">
        {
            "@context": "http://schema.org",
            "@type": "DataCatalog",
            "description": "MyApp Description",
            "keywords": [
                "dynamicValue1",
                "dynamicValue2"
            ],
            "license": "https://www.gnu.org/licenses/gpl-3.0.en.html",
            "name": "MyApp",
            ...
        }
    </script>
</head>

<body>
    <app-root></app-root>
</body>
</html>

Can anyone help me on how to do this? I feel like I've search the whole internet and no one seems to have a similar issue.

What I've tried:

Add :

<script type="application/ld+json" src="src/datacatalog.json"></script>

in index.html and fill datacatalog.json. It doesn't seem to work, when I check the page source code, datacatalog.json seems unknown. When I right-click and save the target, I get this:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Cannot GET /src/datacatalog.json</pre>
</body>
</html>

I'm not sure what to do with this.

Also tried to programatically add the script in an Angular component (from another SO thread I saw) but it did nothing.

Thank you


Solution

  • I've manage to solve my issue with the help of this thread

    Basically, you can write in index.html from an angular component. The component loaded just happens to be the one making request to my backend to get all the data I need to fill the schema.

    Schema.org and google's validator recognize my schema and it works well.