Intercepting a route request using Angular 2 Router

Using an Angular 2 router, I would like to capture an event when a route is requested for activation. In Angular 1.x, I used $ locationChangeSuccess and then checked if the user was registered or not.

I need to do something similar with Angular 2, so I can redirect the user to the login screen if he is not already authenticated.

+5
source share
1 answer

Take a look at CanActivate and CanDeactivate. The official angular docs give an example of creating an administrator, which I found very useful in creating a general login protection feature.

CanActivate is used to check whether the router can switch to a new route, while CanDeactivate is used to check whether the router can move from the current route. If a guard is present on the route, he checks it every time a navigation occurs.

There is a link directly to the example.

+9
source

All Articles