获取Angular2中服务的域名 [英] Get domain name for service in Angular2
问题描述
我需要向同一服务器(另一个端口上的REST API)发出请求.
I need to make request to same server, REST API on another port.
如何在不对服务URL进行全名硬编码的情况下做到这一点?
How can I do this without hardcoding full name in service URLs?
推荐答案
不需要特定于angular2的解决方案.您可以使用 window.location.hostname
来获取当前主机名.
There's no need for an angular2-specific solution. You can use the window.location.hostname
to get the current hostname.
但是,请注意,如果您不想直接使用像window
-object这样的全局变量,则可以提供自己的Window
对象,然后可以将其注入.
Note, however, if you don't want to use global variables like the window
-object directly, you can provide your own Window
object, which then can be injected.
有关详细信息,请参见完整的 Stackblitz Angular示例.
See this full working Stackblitz Angular sample for details.
正如其他人所说,原始答案不再起作用.对于Angular 6+,您需要提供一个注入令牌,以便window
-object也可以在 AOT -build中解决.
As others have stated, the original answer does not work anymore. For Angular 6+, you need to provide an Injection Token, so that the window
-object can be resolved in the AOT-build too.
我建议在这样的单独文件中创建WINDOW_PROVIDERS
数组:
I recommend creating a WINDOW_PROVIDERS
array in a separate file like this:
import { InjectionToken, FactoryProvider } from '@angular/core';
export const WINDOW = new InjectionToken<Window>('window');
const windowProvider: FactoryProvider = {
provide: WINDOW,
useFactory: () => window
};
export const WINDOW_PROVIDERS = [
windowProvider
]
可以将WINDOW_PROVIDERS
常量添加到AppModule
中的providers
数组中,如下所示:
The WINDOW_PROVIDERS
constant can be added to the providers
array in the AppModule
like this:
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule
],
providers: [
WINDOW_PROVIDERS, // <- add WINDOW_PROVIDERS here
SampleService,
],
bootstrap: [AppComponent]
})
export class AppModule { }
在SampleService
中,可以使用已定义的注入令牌注入window
对象 a>像这样:
In the SampleService
, the window
object can be injected by using the defined Injection Token like this:
import { Injectable, Inject } from '@angular/core';
import { WINDOW } from '../window.provider';
@Injectable()
export class SampleService {
constructor(@Inject(WINDOW) private window: Window) {
}
getHostname() : string {
return this.window.location.hostname;
}
}
Angular 2的原始答案
因此,在引导应用程序时,需要为Window
对象设置提供程序.
Original Answer for Angular 2
Therefore you need to set the provider for the Window
-object when bootstrapping your application.
import {provide} from 'angular2/core';
bootstrap(..., [provide(Window, {useValue: window})]);
之后,您可以使用window对象并按如下方式访问主机名:
After that you can use the window object and access the hostname like this:
constructor(private window: Window) {
var hostname = this.window.location.hostname;
}
这篇关于获取Angular2中服务的域名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!