With the Angular 2 Router I'd like to capture an event when a route is requested to be activated. In Angular 1.x I used $locationChangeSuccess, and then checked to see if the user was logged in or not.
I need to do something similar with Angular 2, so I can redirect a user to a login screen if they aren't yet authenticated.
With the Angular 2 Router I'd like to capture an event when a route is requested to be activated. In Angular 1.x I used $locationChangeSuccess, and then checked to see if the user was logged in or not.
I need to do something similar with Angular 2, so I can redirect a user to a login screen if they aren't yet authenticated.
Share Improve this question edited Jul 11, 2016 at 2:09 Beanwah asked Jul 11, 2016 at 1:30 BeanwahBeanwah 1,2902 gold badges17 silver badges28 bronze badges1 Answer
Reset to default 15Take a look at CanActivate and CanDeactivate. The official angular docs give an example of creating an admin guard which I found quite useful when creating a general login guard.
CanActivate is used to check if the router can navigate to the new route, whereas CanDeactivate is used to check if the router can navigate away from the current route. If the guard is present on a route it will check with the guard each time a navigation occurs.
Here is a link directly to the example.