Rob*_*hof 13 angular-routing angular
我想得到这个来自的网址:
this.router.navigate(./somepath, { relativeTo: this.route })
this.route属于那种类型ActivatedRoute.
我试过url: string = route.snapshot.url.join('');但这给了一个空字符串.
vik*_*iks 17
您可以使用激活的路由获取活动URL.
import { ActivatedRoute } from '@angular/router';
constructor(
private activatedRoute: ActivatedRoute) {
console.log(activatedRoute.snapshot['_routerState'].url);
}
Run Code Online (Sandbox Code Playgroud)
小智 7
我有一个类似的问题,我想存储当前 url 中的字符串!有很多解决方案,但没有一个对我有帮助,然后我找到了如何在纯 Js 中做到这一点,所以我在 angular 中尝试了相同的代码行,然后就成功了!!
window.location.href
Run Code Online (Sandbox Code Playgroud)
但真正帮助我的是:
window.location.pathname;
Run Code Online (Sandbox Code Playgroud)
例如:
currentRout: string;
ngOnInit() {
this.currentRout = window.location.href;
console.log(this.currentRout);
}
Run Code Online (Sandbox Code Playgroud)
对我来说,有以下作品:
const url = '/' + this.route.pathFromRoot
.map(route => route.snapshot.url)
.filter(urlSegments => !!urlSegments[0])
.map(([urlSegment]) => urlSegment.path)
.join('/');
Run Code Online (Sandbox Code Playgroud)
这会手动遍历所有父路由并收集结果 URL。
没有黑客攻击,没有使用私有财产。适用于延迟加载的模块。
你想在哪里使用它?
由于您使用的是在构造函数中注入的路由,因此您不能直接在属性 init 中使用路由。因此,您需要在调用构造函数时或之后执行此操作。所以这样的事情应该有效:
export class Test {
url: string
constructor(private route: ActivatedRoute) {
this.url = this.route.snapshot.url.join('');
}
}
Run Code Online (Sandbox Code Playgroud)
官方文档显示了获取当前 url 的不同方法:https : //angular.io/docs/ts/latest/api/router/index/ActivatedRoute-interface.html 这是异步的,所以也许它不是你的后。希望这可以帮助。:)
小智 6
这应该有所帮助:
constructor(router: Router) {
const url = router.url;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
34570 次 |
| 最近记录: |