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

Andrew Stegmaier picture Andrew Stegmaier · Apr 14, 2017 · Viewed 11.7k times · Source

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 context of the app. The app's location varies depending on whether it is development, various staging/testing environments, or production, and I'd like to detect it dynamically so I don't need to maintain a hard-coded list.

A similar question has been posed in the past, but the answers (i.e. use some version of the window.location.hostname or window.location.origin property) only work when the angular2 app is being rendered by the browser.

I would like my app to work with Angular Universal, which means it needs to be rendered on the server side where there is no access to DOM objects like window.location.

Any ideas how to accomplish this? For reference, using asp.net core as the back-end (using the default dotnet new angular template).

Answer

chintan adatiya picture chintan adatiya · Nov 22, 2017

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