Ric*_*ky 8 javascript routes typescript angular-routing angular
如何将之前的路线作为 Angular 中的路径?
我尝试通过此链接使用解决方案,但它不会在首页加载时执行。
constructor(router: Router) {
router.events
.pipe(filter(event => event instanceof NavigationEnd))
.subscribe((event: NavigationEnd) => {
console.log('prev:', event.previousUrl);
this.previousUrl = event.url;
});
}
Run Code Online (Sandbox Code Playgroud)
我使用了RoutesRecognized
和NavigationEnd
,但是它们不起作用。
我在 constructor
和中调用了这个方法ngOnInit
,但是它们都没有在首页加载时执行。
有没有办法获取之前的URL?
谢谢。
jer*_*nis 22
在构造函数中你可以使用
this.router.getCurrentNavigation().previousNavigation.finalUrl.toString()
Run Code Online (Sandbox Code Playgroud)
获取之前的路由路径
请小心,如果在this.router.getCurrentNavigation()
构造函数外部使用,那么生命周期就为时已晚,并且您将始终拥有空值
constructor(private router: Router) {
console.log(this.router.getCurrentNavigation().previousNavigation.finalUrl.toString());
}
Run Code Online (Sandbox Code Playgroud)
您可以尝试navigationStart来解决您第一次无法获取之前路线的问题。
您可以参考以下代码行来了解如何使用它。
ngOnInit(){
this._router.events.filter(e => e instanceof NavigationStart )
.bufferCount(2,1).subscribe(e => {
if(e !== null && e !== undefined) this.orginalPath = e[0]['url'].substr(1)
});
}
Run Code Online (Sandbox Code Playgroud)
如果它解决了您的问题,您甚至可以尝试pairwise()方法。
router.events
.pipe(
filter(e => e instanceof NavigationEnd),
pairwise() // check it's second route load
)
.subscribe((e: any[]) => {
console.log(e);
});
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
20652 次 |
最近记录: |