2016-03-25 23 views

答えて

19

angular2固有のソリューションの必要はありません。 window.location.hostnameを使用すると、現在のホスト名を取得できます。

しかし、windowのようなグローバル変数を直接使用したくない場合は、独自のWindowオブジェクトを用意して注入することができます。したがって、アプリケーションのブートストラップ時にWindowオブジェクトのプロバイダを設定する必要があります。あなたは、ウィンドウオブジェクトを使用して、このように、ホスト名にアクセスすることができます。その後

import {provide} from 'angular2/core'; 
bootstrap(..., [provide(Window, {useValue: window})]); 

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

これはあなたが始める必要があります。

import {LocationStrategy} from '@angular/common'; 

constructor(private locationStrategy:LocationStrategy) { 
    console.log(locationStrategy.prepareExternalUrl('xxx')); 
} 
+1

4+ @angular」から 'インポート{LocationStrategy}を使用します/ common''を参照してくださいhttps://angular.io/api/common/Location –

+0

ヒントをありがとう。それ以来多くのことが変わっています:D –

9

別のオプション角度/プラットフォームブラウザ@から文書を使用することです。

import {DOCUMENT} from '@angular/platform-browser'; 

constructor(@Inject(DOCUMENT) private document) { 
    let url = document.location.protocol +'//'+ document.location.hostname + ':my_port'); 
} 
7

角度2 最新作業溶液:私は私のapp.component.tsに次のコードでそれを達成

app.module.ts

providers: [ 
    {provide: Window, useValue: window}, 
    ... 
] 

youclass.ts

constructor(
    @Inject(Window) private _window: Window 
) { 
    this._baseUrl = `http://${this._window.location.hostname}:3333`; 
}; 
2

import { Component, OnInit, Inject, Injectable } from '@angular/core'; 
import { DOCUMENT } from '@angular/platform-browser'; 

@Component({ 
    selector: 'app-root', 
    templateUrl: './app.component.html', 
    styleUrls: ['./app.component.scss'] 
}) 
export class AppComponent implements OnInit { 

    constructor(@Inject(DOCUMENT) private document: any) { } 

    ngOnInit() { 
     this.domain = this.document.location.hostname; 
     console.log(this.domain); 
    } 
} 

コンソールにドメイン名が表示されます。

0

window.locationをお勧めします。

ただし、あなたもそうのような注射用の角の共通の「場所」のライブラリをインポートし、それを使用してこれを行うことができます。

角用
import { Injectable } from '@angular/core'; 
import { Location } from '@angular/common'; 
const otherPort = 8000; 

@Injectable() 
export class ServiceOrComponentName { 
    constructor(location: Location) { 
    this.baseUrl = location._platformStrategy._platformLocation._location.protocol + 
     '//' + location._platformStrategy._platformLocation._location.hostname + 
     ':' + otherPort; 
    } 
} 
関連する問題