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

前端之家收集整理的这篇文章主要介绍了如何测试Angular2中是否存在路由?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在Angular2中,如何检查路由是否存在?

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

登录时我有:

this.router.navigate([this.authService.redirectUrl]);

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

if (this.authService.redirectUrl is a valid route) {
  this.router.navigate([this.authService.redirectUrl]);
}

有没有办法检查这个?

解决方法

您可以使用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');
  });

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

猜你在找的Angularjs相关文章