如何使用TypeScript在Angular 2中的浏览器中获取当前URL?

时间:2016-06-13 18:08:36

标签: javascript typescript angular

我需要在Angular 2应用程序中获取浏览器中的当前URL。

在JavaScript中,我们通常使用window对象来完成。

如何使用TypeScript在Angular 2中执行此操作?

感谢。

6 个答案:

答案 0 :(得分:37)

这已经很晚了,但我觉得值得更新。从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);
    }
}

答案 1 :(得分:20)

没有必要导入复杂的包或注入一些东西。只需使用window.location上可以找到的方法!

如:

  • window.location.href为您提供完整的网址
  • window.location.hostname为您提供主机名
  • window.location.origin使用此命令可以获得带协议的主机名(例如https://)
  • 以及更多内容,如您所见:some ways
  

对于IE< = 10个用户:location.origin可能无法使用,那么您必须使用location.protocol + "//" + location.hostname或使用填充或包裹,如click me

答案 2 :(得分:6)

导入ActivatedRoute,(如果需要,也可以导入路由器的其余部分)

import { ActivatedRoute, Params, Router, UrlSegment } from '@angular/router';

确保将其注入构造函数,

constructor(private route: ActivatedRoute) { ... }

并且在ngOnInit上,您可以使用this.route来检查网址。例如,所有段都在一个数组中,你可以像@ibgib建议的那样将它们串在一起,如下所示:

let path = this.route.snapshot.url.join('/');

给你类似"火星/卫星/恐惧症"。

答案 3 :(得分:5)

你可以

另见

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

答案 4 :(得分:5)

对于未来的旅行者来说,很多其他答案都很棒。另一个选择,如果您想要路径名之前的所有内容(例如https://example.com),那么您可以使用:

window.location.origin

这是关于您可以使用的不同window.location属性的W3文章: http://www.w3schools.com/js/js_window_location.asp

干杯!

答案 5 :(得分:3)

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;
}
相关问题