2016-06-13 60 views

回答

4

可以

又見

How do I get the absolute path of the current page in Angular 2?

+0

謝謝..它的作品!然而,當我嘗試使用location.path()它什麼也沒有顯示...反正它的工作,如果我直接使用窗口對象..再次感謝:) – Kevin

+0

你注入'構造函數(位置:位置){console.log(位置。路徑();}' –

+0

是 '構造?(位置:位置) { 警報(location.prepareExternalUrl(location.path()); 的console.log(location.path());} ' – Kevin

28

這是晚,但我認爲這是值得更新。從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); 
    } 
} 
+0

'出口'DOCUMENT'在'@ angular/common''中找不到'4.1.3'。 – Deilan

+0

@Deilan我有一個快速檢查的來源,它仍然存在https://github.com/angular/angular/blob/master/packages/common/src/dom_tokens.ts – JayChase

5

導入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('/'); 

給你像「火星/衛星/火衛一」。

+1

我個人喜歡這個ve rsion。但是,'this.route.url'是一個'Observable '。可能不是使用'forEach'來枚舉可能產生多次迭代的observable,而是使用'this.route.snapshot.url.join('/')'來代替? – ibgib

+1

謝謝@ibgib - 在答案中使用了你的代碼。更多的習慣用法。 –

+0

嗯我使用這種方法時獲得空路徑,即使我的網址不是根。 – thienedits

6

對於未來的旅行者,很多其他答案都很棒。另一種選擇,如果你想要的路徑名之前的一切(例如https://example.com),那麼你可以使用:

window.location.origin

這裏有不同的window.location性能W3文章中,你可以使用: http://www.w3schools.com/js/js_window_location.asp

乾杯!

+0

這不起作用。錯誤與:ReferenceError:未定義窗口 – Neurothustra

+0

@Neurothustra您可能會嘗試打開一個新問題併發布您的代碼。我猜這是某種競爭條件。 Window被燒入瀏覽器本身,所以我猜這是一個本地問題。 – kbpontius

9

沒有必要導入複雜的軟件包或注入某些東西。只需使用你可以在window.location找到的方法!

如:

  • window.location.href爲您提供了完整的URL
  • window.location.hostname給你的主機名
  • window.location.origin用這個命令你得到協議中的主機名(例如,https://開頭)
  • 以及更多,你可以在這裏看到:click me
+1

感謝分享。 –

2

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; 
} 
相關問題