Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the page hostname in Angular 2?

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.

like image 386
Stefan D Avatar asked Feb 07 '23 09:02

Stefan D


1 Answers

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 }
like image 72
Leo Avatar answered Feb 21 '23 08:02

Leo