在我的 Angular Route 中,我定义我正在使用哈希策略:
// app-routing-module.ts
@NgModule({
imports: [
RouterModule.forRoot(routes, {
useHash: true
})
],
//...
当我想测试当前的 Router url 时,我运行以下代码:
import { Router } from '@angular/router';
// ..
constructor(private _router: Router) {}
getUrl() {
return this._router.url; // always return '/'
}
this._router.url
始终等于“/”。但是,如果我测试 window.location.href
,我会得到不同的值(真正的完整网址)。
在使用哈希策略时,如何获取当前的router-url(以Angular方式,而不是通过窗口对象)?
最佳答案
您可以像这样使用PlatformLocation
类:
import { PlatformLocation } from '@angular/common';
constructor(private pLocation: PlatformLocation) { }
getUrl() {
return (pLocation as any).location.href;
}
我编码(pLocation as any)
的原因是location
没有显示 typescript 智能感知,正如你所看到的,它没有显示在Angular docs中,但它就在那里,您可以使用它。
关于javascript - Angular - 使用哈希策略时如何获取 URL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59521977/