我需要在Angular 2应用程序的浏览器中获得当前的URL。
在JavaScript中,我们通常使用window对象。
我如何使用TypeScript在Angular 2中做到这一点?
谢谢。
发布于 2016-11-22 10:55:03
虽然为时已晚,但我认为它值得更新。从Angular2最终版本开始,您可以从@angular/common导入文档,并使用该文档到达相应的位置。
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);
}
}
发布于 2016-11-29 21:08:09
导入ActivatedRoute (如果需要,还可以导入其余的路由器内容)
import { ActivatedRoute, Params, Router, UrlSegment } from '@angular/router';
确保它被注入到构造函数中,
constructor(private route: ActivatedRoute) { ... }
在ngOnInit上,你可以使用this.route
来检查网址。例如,所有的段都在一个数组中,您可以按照@ibgib的建议将其串在一起,如下所示:
let path = this.route.snapshot.url.join('/');
给你一些像“火星/卫星/火卫一”之类的东西。
发布于 2017-02-01 03:16:33
对于未来的旅行者来说,很多其他的答案都很棒。另一种选择是,如果您想要路径名之前的所有内容(例如https://example.com
),则可以使用:
window.location.origin
这里有一篇关于您可以使用的不同window.location
属性的W3文章:http://www.w3schools.com/js/js_window_location.asp
干杯!
https://stackoverflow.com/questions/37796449
复制相似问题