6

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?

Robert Lavoie
  • 81
  • 1
  • 4

1 Answers1

9

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));
});
...
Ivan Kalashnik
  • 411
  • 7
  • 12