Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

angular - Get domain name for service in Angular2

I need to make request to same server, REST API on another port.

How can I do this without hardcoding full name in service URLs?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There's no need for an angular2-specific solution. You can use the window.location.hostname to get the current hostname.

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.

See this full working Stackblitz Angular sample for details.

Updated Answer for Angular 6+

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. Otherwise you will get the error "Can't resolve all parameters".

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
]

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 { }

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;
    }
}

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})]);

After that you can use the window object and access the hostname like this:

constructor(private window: Window) {
   var hostname = this.window.location.hostname;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...