How to get full base URL (including server, port and protocol) in Angular Universal?
I have bit of working code with angular 5 and angular universal
in server.ts replace this
app.engine('html', (_, options, callback) => {
let engine = ngExpressEngine({
bootstrap: AppServerModuleNgFactory,
providers: [
{ provide: 'request', useFactory: () => options.req, deps: [] },
provideModuleMap(LAZY_MODULE_MAP)
]
});
engine(_, options, callback);
});
and in Angular side you can get host with below code
export class AppComponent {
constructor(
private injector: Injector,
@Inject(PLATFORM_ID) private platformId: Object
) {
console.log('hi, we\'re here!');
if (isPlatformServer(this.platformId)) {
let req = this.injector.get('request');
console.log("locales from crawlers: " + req.headers["accept-language"]);
console.log("host: " + req.get('host'));
console.log("headers: ", req.headers);
} else {
console.log('we\'re rendering from the browser, there is no request object.');
}
}
}
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
}
}