如何测试Angular2中是否存在路由? [英] How to test if a route exists in Angular2?

查看:131
本文介绍了如何测试Angular2中是否存在路由?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In Angular2 how do I check if a route exists?

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

I have a method that remembers which route to navigate to if the user is not authorised.

登录后,我有:

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

但是我只想在redirectUrl引用有效路由的情况下进行导航,例如..

But I only want to navigate IF the redirectUrl references a valid route, something like ..

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

有什么办法可以检查吗?

Is there any way to check this?

推荐答案

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

You can check if the route exists like that using the promise way :

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块中执行一些代码.

If the route is defined, redirection will happen. If not, you can execute some code in the catch block.

这篇关于如何测试Angular2中是否存在路由?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆