获取Angular Universal中的主机名和路径名信息

时间:2017-06-09 14:25:47

标签: angular angular-universal

有没有人知道如何在Angular universal中访问主机名和路径名信息?

在客户端应用程序中,您可以访问具有该信息的窗口对象。

我只需要在服务器上提供这些信息吗?

1 个答案:

答案 0 :(得分:6)

使用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);
  }
}

没有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));
});
...