问题描述
我需要在Angular 2中获取页面的子域,因为它与路由有关.我看到在多次中断发布后,Angular 2中的路由器服务仍然没有域的概念.同样,位置服务会忽略URL的主机部分.
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.
如果您不想直接使用window.location
,则可以将其注入,即,如果仅需要主机,则可以将以下内容添加到模块提供程序中:
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) { }
确保您可以提供整个window
对象:
For sure you can provide whole window
object:
{ provide: Window, useValue: window }
然后注入它:
constructor(private window: Window) { }
更新
第一个选项在AOT版本上不起作用,您应该改用工厂:
first option won't work on AOT builds, you should use a factory instead:
export function hostFactory() { return window.location.host; }
然后是提供者:
{ provide: 'HOSTNAME', useFactory: hostFactory }
这篇关于如何在Angular 2中获取页面主机名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!