How to get the page hostname in Angular 2?

不羁岁月 提交于 2019-12-23 12:52:13

问题


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.


回答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 }



回答2:


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



来源:https://stackoverflow.com/questions/38864584/how-to-get-the-page-hostname-in-angular-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!