Angular - 使用哈希策略时如何得到 URL?

Angular - How to get URL when using Hash-Strategy?

在我的 Angular 路由中,我定义我正在使用哈希策略:

// app-routing-module.ts
@NgModule({
  imports: [
    RouterModule.forRoot(routes, {
      useHash: true
    })
  ],
//...

当我想测试当前路由器url时,我运行这个代码:

import { Router } from '@angular/router';
// ..

constructor(private _router: Router) {}

getUrl() {
  return this._router.url; // always return '/'
}

this._router.url 总是等于'/'。但是,如果我测试 window.location.href,我会得到一个不同的值(真正完整的 url)。

如何在使用 哈希策略[=25= 时获取当前路由器-url(以 Angular 方式,而不是通过 window 对象) ]?

你应该使用 ActivatedRoute 得到 URL 正如 Numichi 提到的

您可以这样使用 PlatformLocation class:

import { PlatformLocation } from '@angular/common';

constructor(private pLocation: PlatformLocation) { }

getUrl() {
  return (pLocation as any).location.href;
}

我编码 (pLocation as any) 的原因是 location 没有显示它 typescript intellisense,你可以看到它没有显示在 Angular docs 中,但它在那里,你可以使用它。

SIMPLE DEMO