Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test if a route exists in 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.

On login I have:

this.router.navigate([this.authService.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?

like image 530
danday74 Avatar asked Mar 13 '17 12:03

danday74


1 Answers

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.

like image 55
Theo Godard Avatar answered Oct 04 '22 02:10

Theo Godard