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

Kev*_*vin 29 javascript typescript angular

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

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

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

谢谢.

Jay*_*ase 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);
    }
}
Run Code Online (Sandbox Code Playgroud)


Flo*_*geb 21

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

如:

  • window.location.href 为您提供完整的URL
  • window.location.hostname 为您提供主机名
  • window.location.origin使用此命令,您将获得带有协议的主机名(例如https://)
  • 你可以在这里看到更多:点击我

对于IE <= 10个用户:location.origin可能无法使用,那么您必须使用location.protocol + "//" + location.hostname或使用polyfill或包location-origin

  • 请注意,不建议将Angular直接与window一起使用,因为在预渲染时它在服务器端不可用,因此会破坏Angular Universal(如果您打算建立一个SEO友好站点,则很重要)。 (3认同)

Gün*_*uer 5

您可以

也可以看看

如何获取Angular 2中当前页面的绝对路径?


Ral*_*lle 5

导入ActivatedRoute,(如果你愿意,也可以输入其余的路由器)

import { ActivatedRoute, Params, Router, UrlSegment } from '@angular/router';
Run Code Online (Sandbox Code Playgroud)

确保它被注入构造函数中,

constructor(private route: ActivatedRoute) { ... }
Run Code Online (Sandbox Code Playgroud)

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

let path = this.route.snapshot.url.join('/');
Run Code Online (Sandbox Code Playgroud)

给你一些像"火星/卫星/恐怖"的东西.

  • 嗯,即使我的 url 不是根,我在使用此方法时也会得到空路径。 (2认同)

kbp*_*ius 5

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

window.location.origin

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

干杯!