How to test if a route exists in Angular2?

我只是一个虾纸丫 提交于 2019-12-05 02:20:21

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');
  });

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

I have the handling for preventing for the urls that doesn't exist

{path: 'dashboard', component: DashboardComponent}
{path: 'demo/:demo', component: DemoComponent},
{path: '**', redirectTo: '/dashboard'}

** means all the paths that are not able to redirect

Maybe with something like this :

redirectUrl: string;

this.redirectUrl = this.authService.redirectUrl ? this.authService.redirectUrl : '/home';
this.router.navigate([this.redirectUrl]);

This will check if the redirect url exist, if not it will redirect to the alternative route /home (you can change home to whatever you like)

Edit: If you just want to check if this.authService.redirectUrl, you can try something like this :

if(this.authService.redirectUrl){
   //do what you want
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!