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.
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With