我需要在我的Angular 2應用程序中獲取瀏覽器中的當前URL。如何使用TypeScript在Angular 2中的瀏覽器中獲取當前網址?
在JavaScript中,我們通常使用窗口對象來完成它。
如何在Angular 2中使用TypeScript來做到這一點?
謝謝。
我需要在我的Angular 2應用程序中獲取瀏覽器中的當前URL。如何使用TypeScript在Angular 2中的瀏覽器中獲取當前網址?
在JavaScript中,我們通常使用窗口對象來完成它。
如何在Angular 2中使用TypeScript來做到這一點?
謝謝。
可以
Location
和location.path()
獲取URL(見Location and HashLocationStrategy stopped working in beta.16)window.location.pathname
又見
How do I get the absolute path of the current page in Angular 2?
這是晚,但我認爲這是值得更新。從Angular2最終版本開始,您可以從@ angular/common導入DOCUMENT,並使用它來到達位置。
import { Component, Inject } from '@angular/core';
import { DOCUMENT } from '@angular/common';
...
export class YourComponent {
constructor(@Inject(DOCUMENT) private document: Document) {
console.log(this.document.location.href);
}
}
導入ActivatedRoute,(和路由器的東西休息過,如果你想)
import { ActivatedRoute, Params, Router, UrlSegment } from '@angular/router';
確保它注入構造,
constructor(private route: ActivatedRoute) { ... }
和ngOnInit您可以使用this.route
檢查URL。例如,所有的部分都在一個數組,你可以串在一起,@ibgib建議,像這樣:
let path = this.route.snapshot.url.join('/');
給你像「火星/衛星/火衛一」。
我個人喜歡這個ve rsion。但是,'this.route.url'是一個'Observable
謝謝@ibgib - 在答案中使用了你的代碼。更多的習慣用法。 –
嗯我使用這種方法時獲得空路徑,即使我的網址不是根。 – thienedits
對於未來的旅行者,很多其他答案都很棒。另一種選擇,如果你想要的路徑名之前的一切(例如https://example.com
),那麼你可以使用:
window.location.origin
這裏有不同的window.location
性能W3文章中,你可以使用: http://www.w3schools.com/js/js_window_location.asp
乾杯!
這不起作用。錯誤與:ReferenceError:未定義窗口 – Neurothustra
@Neurothustra您可能會嘗試打開一個新問題併發布您的代碼。我猜這是某種競爭條件。 Window被燒入瀏覽器本身,所以我猜這是一個本地問題。 – kbpontius
沒有必要導入複雜的軟件包或注入某些東西。只需使用你可以在window.location
找到的方法!
如:
window.location.href
爲您提供了完整的URLwindow.location.hostname
給你的主機名window.location.origin
用這個命令你得到協議中的主機名(例如,https://開頭)感謝分享。 –
這Link幫助我:
public static getCurrentAbsoluteSiteUrl(): string {
if (window
&& "location" in window
&& "protocol" in window.location
&& "pathname" in window.location
&& "host" in window.location) {
return window.location.protocol + "//" + window.location.host + window.location.pathname;
}
return null;
}
同樣會應該爲你工作 –
@KaushikThanki謝謝!有用。愚蠢的問題,我猜:P應該剛剛嘗試.. – Kevin