私は別のポートで同じサーバ、残りのapiにリクエストをする必要があります。Angular2でサービスのドメイン名を取得するには
サービスURLに完全な名前をハードコードしないと、どうすればいいですか?
私は別のポートで同じサーバ、残りのapiにリクエストをする必要があります。Angular2でサービスのドメイン名を取得するには
サービスURLに完全な名前をハードコードしないと、どうすればいいですか?
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;
}
これはあなたが始める必要があります。
import {LocationStrategy} from '@angular/common';
constructor(private locationStrategy:LocationStrategy) {
console.log(locationStrategy.prepareExternalUrl('xxx'));
}
別のオプション角度/プラットフォームブラウザ@から文書を使用することです。
import {DOCUMENT} from '@angular/platform-browser';
constructor(@Inject(DOCUMENT) private document) {
let url = document.location.protocol +'//'+ document.location.hostname + ':my_port');
}
角度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`;
};
:
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);
}
}
コンソールにドメイン名が表示されます。
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;
}
}
4+ @angular」から 'インポート{LocationStrategy}を使用します/ common''を参照してくださいhttps://angular.io/api/common/Location –
ヒントをありがとう。それ以来多くのことが変わっています:D –