How to get full base URL (including server, port and protocol) in Angular Universal?

后端 未结 4 2351
说谎
说谎 2020-12-11 03:15

I need to get the full base URL (e.g. http://localhost:5000 or https://productionserver.com) of my Angular 2 app so that I can pass it along to a 3rd party service in the co

4条回答
  •  醉话见心
    2020-12-11 03:45

    Now I'm using the server.ts ngExpressEngine:

    import { ngExpressEngine } from '@nguniversal/express-engine';
    
    const {AppServerModuleNgFactory, LAZY_MODULE_MAP} = require('./dist/server/main.bundle');
    
        const {provideModuleMap} = require('@nguniversal/module-map-ngfactory-loader');
    
        app.engine('html', ngExpressEngine({
            bootstrap: AppServerModuleNgFactory,
            providers: [
                provideModuleMap(LAZY_MODULE_MAP)
            ]
        }));
    

    And after that I can use in location.service.ts:

    constructor(@Optional() @Inject(REQUEST) private request: any,
                @Optional() @Inject(RESPONSE) private response: any,
                @Inject(PLATFORM_ID) private platformId: Object)
    {
      if (isPlatformServer(this.platformId))
      {
        console.log(this.request.get('host’)); // host on the server
      } else
      {
        console.log(document.location.hostname); // host on the browser
      }
    }
    

提交回复
热议问题