如何测试Angular2中是否存在路由?

dan*_*y74 9 angular2-routing angular

在Angular2中,如何检查路由是否存在?

我有一个方法,可以记住如果用户未经授权,导航到哪个路由.

登录时我有:

this.router.navigate([this.authService.redirectUrl]);
Run Code Online (Sandbox Code Playgroud)

但我只想导航如果redirectUrl引用了一个有效的路由,比如..

if (this.authService.redirectUrl is a valid route) {
  this.router.navigate([this.authService.redirectUrl]);
}
Run Code Online (Sandbox Code Playgroud)

有没有办法检查这个?

小智 8

您可以使用promise方式检查路由是否存在:

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');
  });
Run Code Online (Sandbox Code Playgroud)

如果定义了路由,则会发生重定向.如果没有,您可以在catch块中执行一些代码.

  • 我想测试是否存在不重定向的路线,所以这个答案对我不起作用。 (4认同)