How to pass variable from Express.js to Angular11 universal SSR

Viewed 1058

Quick question, how we can pass to angular-universal HTML components or to the main app index.html variables from expressjs, like available from expressjs to ejs or pug?

        app.get('*', (req, res) => {
          res.render('index', { req, messsage: 'This is your message' });
        }

Ejs can get variable from expressjs like this:

    <h1><%= message %></h1>

Pug can get variable from expressjs like this:

 h1= message

We need to display a message from expressjs when the pages load or reloads into the view-source not in the shadow dom or DOM or as "inspect" on chrome. Must be on the view-source in the render HTML source file.

We using angular 11 SSR universal with expressjs.

Any ideas or is impossible?

1 Answers

You can provide values from the server and use them in your components/services

server.ts

app.get('*', (req, res) => {
      res.render('index', { req, res,  providers: [{ provide: 'message', useValue: 'This is your message' }] })

component.ts

import {Injectable, Inject, PLATFORM_ID, Optional} from '@angular/core';
import {isPlatformBrowser} from "@angular/common";
import {TransferState, makeStateKey} from '@angular/platform-browser';

//Message here is optional because it is only provided in SSR mode

constructor(@Inject(PLATFORM_ID) private platformId: Object,
@Optional() @Inject('message') public message: string,
 private readonly transferState: TransferState)
{         
    const storeKey = makeStateKey<string>('messageKey');
    if(isPlatformBrowser(this.platformId))//get message from transferState if browser side
    {
        this.message = this.transferState.get(storeKey, 'defaultMessageValue');
    }
    else //server side: get provided message and store in in transfer state
    {
        this.transferState.set(storeKey, this.message);
    }
    
    
    

component.html

<div *ngIf="message">Message from server : {{message}} </div>

With that code, your message will appear in the html rendered by the server (which you can see using view source).

Thanks to transfer state, the message is also available client side

Edit I added instructions so that the message is still available client side

Related