Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
124
rated 0 times [  127] [ 3]  / answers: 1 / hits: 17359  / 8 Years ago, mon, july 11, 2016, 12:00:00

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.


More From » angular

 Answers
44

Take 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.


[#61433] Friday, July 8, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
josh

Total Points: 391
Total Questions: 112
Total Answers: 90

Location: Aruba
Member since Fri, Jun 24, 2022
2 Years ago
;