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.
Instead of “href” attribute of anchor tag, we use the “routerLink” attribute of Angular. The routerLink attribute allows us to link to a specific route of the Application.
ActivatedRoutelink. Provides access to information about a route associated with a component that is loaded in an outlet.
To access the route parameters, we use route.snapshot , which is the ActivatedRouteSnapshot that contains information about the active route at that particular moment in time. The URL that matches the route provides the productId . Angular uses the productId to display the details for each unique product.
ActivatedRoute Contains the information about a route associated with a component loaded in an outlet. It can also be used to pass data from one component to another component using route such as Id, flag, state etc.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With