Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get hostname and pathname information within Angular Universal

Does anyone here know how to get access to hostname and pathname information in Angular universal?

Within the client side app you have access to the window object which has that information.

I just need that information on the server?

like image 346
Robert Lavoie Avatar asked Mar 09 '23 21:03

Robert Lavoie


1 Answers

With ngExpressEngine:

server.ts:

...
app.engine('html',  (_, options, callback) => {
  let engine = ngExpressEngine({
    bootstrap: ServerAppModule,
    providers: [ { provide: 'host', useFactory: () => options.req.get('host') } ]
  });

  engine(_, options, callback)
})
...

app.component.ts:

import { Inject, Injector, PLATFORM_ID } from '@angular/core';
import { DOCUMENT, isPlatformServer } from '@angular/common';

...

constructor(@Inject(DOCUMENT) private document, private injector: Injector, @Inject(PLATFORM_ID) private platformId: Object) {
  if (isPlatformServer(this.platformId)) {
    console.log(this.injector.get('host'))
  } else {
    console.log('document: ', document.location.hostname);
  }
}

Without ngExpressEngine:

server.ts:

...
app.engine('html', (_, options, callback) => {
  const opts = {
    document: template,
    url: options.req.url,
    extraProviders: [{ provide: 'host', useFactory: () => options.req.get('host') }]
  };
  renderModuleFactory(AppServerModuleNgFactory, opts)
    .then(html => callback(null, html));
});
...
like image 108
Ivan Kalashnik Avatar answered Mar 11 '23 10:03

Ivan Kalashnik