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

Kev*_*ker 20 angular

我基本上遇到了这个问题,我需要引用当前路径来使用渐变,但还没有弄清楚如何将解决方案转换为Angular 2.

Gün*_*uer 33

constructor(location:Location) {
  console.log(location.prepareExternalUrl(location.path()));
}
Run Code Online (Sandbox Code Playgroud)

https://angular.io/docs/ts/latest/api/common/index/Location-class.html#!#prepareExternalUrl-anchor

window.location 提供更多信息

Plunker的例子

  • 这不适用于角度5它只给了我路径 (14认同)
  • @GünterZöchbauer这只显示在基地址之后!任何更新? (4认同)

gud*_*duf 23

你可以使用DOCUMENT注射@angular/common.

import { Component, Inject } from '@angular/core';
import { DOCUMENT } from '@angular/common';

@Component({...})
class SomeComponent {
  constructor(@Inject(DOCUMENT) document: any) {
    console.log(document.location.href);
  }
}
Run Code Online (Sandbox Code Playgroud)


Sag*_*gar 14

位置对象

document.location对象是您的一站式解决方案.

使用文档中位置对象内的属性以您需要的方式获取路径.让我们看一个例子.

因此对于 https://www.google.com/images

  • document.location.href 将返回 https://www.google.com/images
  • document.location.origin 将返回 https://www.google.com
  • document.location.protocol 将返回 https:
  • document.location.host 将返回 google.com
  • document.location.hostname 将返回 google
  • document.location.pathname 将返回 /images