在Angular2中,如何检查路线是否存在?
如果用户未获得授权,我有一种方法可以记住导航到哪条路线。
登录时我有:
this.router.navigate([this.authService.redirectUrl]);
但我只想导航如果redirectUrl引用了一个有效的路由,比如......
if (this.authService.redirectUrl is a valid route) {
this.router.navigate([this.authService.redirectUrl]);
}
有没有办法检查这个?
答案 0 :(得分:8)
您可以使用承诺方式检查路线是否存在:
this.router.navigate(['redirect'])
.then(data => {
console.log('Route exists, redirection is done');
})
.catch(e => {
console.log('Route not found, redirection stopped with no error raised');
});
如果定义了路由,则会发生重定向。如果没有,您可以在catch块中执行一些代码。
答案 1 :(得分:1)
我有防止不存在的网址的处理
{path: 'dashboard', component: DashboardComponent}
{path: 'demo/:demo', component: DemoComponent},
{path: '**', redirectTo: '/dashboard'}
**
表示无法重定向的所有路径
答案 2 :(得分:0)
也许有这样的事情:
redirectUrl: string;
this.redirectUrl = this.authService.redirectUrl ? this.authService.redirectUrl : '/home';
this.router.navigate([this.redirectUrl]);
这将检查重定向网址是否存在,如果不存在,它将重定向到备用路由/home
(您可以将主页更改为您想要的任何内容)
修改强>
如果您只是想检查一下this.authService.redirectUrl
,可以尝试这样的事情:
if(this.authService.redirectUrl){
//do what you want
}