【发布时间】:2021-08-06 12:12:21
【问题描述】:
我想得到来自这个的 url:
this.router.navigate(./somepath, { relativeTo: this.route })
this.route 的类型为 ActivatedRoute。
我尝试了url: string = route.snapshot.url.join('');,但这给出了一个空字符串。
【问题讨论】:
我想得到来自这个的 url:
this.router.navigate(./somepath, { relativeTo: this.route })
this.route 的类型为 ActivatedRoute。
我尝试了url: string = route.snapshot.url.join('');,但这给出了一个空字符串。
【问题讨论】:
您可以使用激活的路由来获取活动的 URL。
import { ActivatedRoute } from '@angular/router';
constructor(
private activatedRoute: ActivatedRoute) {
console.log(activatedRoute.snapshot['_routerState'].url);
}
【讨论】:
(<RouterStateSnapshot>activatedRoute['_routerState']).url,如果你喜欢的话。
_routerState 属性可能出于某种原因是私有的。我在从延迟加载的模块中获取完整 url 时遇到了问题,它对我有用。
这应该会有所帮助:
constructor(router: Router) {
const url = router.url;
}
【讨论】:
我有一个类似的问题,我想存储当前 url 中的字符串!有很多解决方案,但没有一个对我有帮助,然后我找到了如何在纯 Js 中做到这一点,所以我在 angular 中尝试了同一行代码,然后它成功了!!
window.location.href
但真正帮助我的是:
window.location.pathname;
例如:
currentRout: string;
ngOnInit() {
this.currentRout = window.location.href;
console.log(this.currentRout);
}
【讨论】:
对我来说,以下作品:
const url = '/' + this.route.pathFromRoot.map(r => r.snapshot.url).filter(f => !!f[0]).map(([f]) => f.path).join('/');
这会手动遍历所有父路由并收集结果 URL。
没有黑客,没有使用私有财产。适用于延迟加载的模块。
【讨论】:
你想在哪里使用它?
由于您使用的是在构造函数中注入的路由,因此您不能直接在属性 init 中使用路由。因此,您需要在调用构造函数时或之后执行此操作。所以这样的事情应该可以工作:
export class Test {
url: string
constructor(private route: ActivatedRoute) {
this.url = this.route.snapshot.url.join('');
}
}
官方文档显示了获取当前 url 的另一种方式:https://angular.io/docs/ts/latest/api/router/index/ActivatedRoute-interface.html 这是异步的,所以也许这不是你想要的。希望这可以帮助。 :)
【讨论】:
我可以使用以下代码 sn-p 获取当前页面 URL
constructor(private activatedRoute: ActivatedRoute){}
const url = this.activatedRoute['_routerState'].snapshot.url;
【讨论】:
我是这样理解的:
import { filter, take } from 'rxjs/operators';
constructor(
private router: Router
) {
this.router.events.pipe(
filter(event => event instanceof ChildActivationEnd),
take(1),
).subscribe(event=>{
const url = event.snapshot['_routerState'].url;
console.log('url', url);
});
}
【讨论】:
我得到它并没有那么老套。我也使用 lodash 来展平数组。
_.flatten(this.route.pathFromRoot.map(route => route.snapshot.url)).join('/')
【讨论】:
我使用了 Phillip Patton 的解决方案,但是 IE/Edge 不支持 flat() 功能,所以下面是一个替代方案:
'/' + this.route.pathFromRoot.map(r => r.snapshot.url).reduce((acc, val) => acc.concat(val), []).map(f => f.path).join('/');
【讨论】:
这对我有用,并考虑了根目录的完整路径。
添加返回嵌套数组的flat() 函数有助于后续的map 函数。它只需要处理平面数组,而不是在第二次 map 调用中以某种方式取消对嵌套数组的引用。
'/' + route.pathFromRoot.map(r => r.snapshot.url).flat().map(f => f.path).join('/')
【讨论】:
constructor(
readonly location: Location
)
然后
this.location.path()
这将获得网址
【讨论】: