Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What all could be the reasons for a NavigationCancel event to get triggered?

I have a subscription for router events in angular2, When I console the events, I find a NavigationCancel event with reason: "". Curious to know what all could be the reasons for a NavigationCancel to get triggered. Not only with an empty reason but in general.

like image 336
Ashish Ranjan Avatar asked Jun 05 '17 14:06

Ashish Ranjan


People also ask

Which event is triggered when a navigation starts?

NavigationStartlink. An event triggered when a navigation starts.

How do I stop Routerlink?

Angular's standard way to enable/disable navigation from a given route is to implement a CanDeactivate route guard. Similarly, you can implement a CanActivate route guard to enable/disable navigation to a given route.

What is NavigationStart in angular?

The Angular Routers triggers several events starting with when the Navigation starts ( NavigationStart ) and also when the Navigation end ( NavigationEnd ) successfully. It is triggered when the navigation is canceled either by the user ( NavigationCancel ) or due to an error in the navigation ( NavigationError).

What is angular route Guard?

Angular route guards are interfaces provided by Angular which, when implemented, allow us to control the accessibility of a route based on conditions provided in class implementation of that interface. Here are some types of Angular guards: CanActivate, CanActivateChild, CanLoad, CanDeactivate and Resolve.


2 Answers

NavigationCancel will be triggered when you are trying to naviggate to a route and navigated route children can not be loaded (CanLoad guard) or route itself cannot be activated (CanActivate guard)

you may use {enableTracing : true} while configuring RouterModule to see all events, and analyze further.

Hope this helps!!

like image 198
Madhu Ranjan Avatar answered Nov 10 '22 21:11

Madhu Ranjan


This is late, but i hope it might help someone else, as I had struggled with this also.

So, another reason this could be happening is that the navigation event is triggered twice.

This happened to me by mistake, because i had a component with a routerLink directive that had an input binding with the same name:

my-component Class:

@Input() routerLink: string[];

my-component Template:

...
<a [routerLink]="routerLink">
...

The parent component template was like this :

...
<my-component
   [routerLink]="somePath"
   ...
>

Which was actually creating another routerLink directive binding. As a result the navigation event was firing twice, almost simultaneously, which produced the NavigationCancel event.

like image 43
ktsangop Avatar answered Nov 10 '22 19:11

ktsangop