How to get the page hostname in Angular 2?

10,700

Solution 1

There is no build in way to get current host.

If you don't want to use window.location directly you can inject it, i.e. if you need only host you can add the following into module providers:

{ provide: 'HOST', useValue: window.location.host }

then you can inject it in component or service:

constructor(@Inject('HOST') private host: string) { }

For sure you can provide whole window object:

{ provide: Window, useValue: window }

And then inject it:

constructor(private window: Window) { }

UPDATE

first option won't work on AOT builds, you should use a factory instead:

export function hostFactory() { return window.location.host; }

and then provider:

{ provide: 'HOSTNAME', useFactory: hostFactory }

Solution 2

I got the hostname just using this: window.location.hostname

Share:
10,700
Stefan D
Author by

Stefan D

Updated on June 25, 2022

Comments

  • Stefan D
    Stefan D almost 2 years

    I need to get the subdomain of a page in Angular 2 because it is relevant to the route. I see that after multiple breaking releases the Router service in Angular 2 still has no notion of domain. Similarly, the Location service is ignorant of the host part of the URL.

  • Snook
    Snook over 4 years
    Your updated solution is the best solution, because you can mock it in test.