【问题标题】:Get hostname and pathname information within Angular Universal在 Angular Universal 中获取主机名和路径名信息
【发布时间】:2017-11-11 14:53:24
【问题描述】:

这里有人知道如何访问 Angular 通用的主机名和路径名信息吗?

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

我只需要服务器上的这些信息?

【问题讨论】:

    标签: angular angular-universal


    【解决方案1】:

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

    【讨论】:

    • 我收到了错误Error: StaticInjectorError[{provide:"host", useFactory:useFactory}]: 'deps' required。我的通用版本是5.0.0-beta.6
    • 换行到这个{ provide: 'host', useFactory: () => options.req.get('host'), deps: [] }
    • injector.get('host') used as is shown here is deprectaed.
    猜你喜欢
    • 2020-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-13
    • 2016-09-08
    • 2017-09-10
    • 2011-02-18
    相关资源
    最近更新 更多