Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Intercept Route Request with Angular 2 Router

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.

like image 587
Beanwah Avatar asked Jul 11 '16 01:07

Beanwah


People also ask

What would you use in angular 2 to define routes?

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.

Why do we use ActivatedRoute in Angular?

ActivatedRoutelink. Provides access to information about a route associated with a component that is loaded in an outlet.

How does Angular routing handle route parameters?

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.

What is ActivatedRoute in Angular example?

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.


1 Answers

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.

like image 160
Keifer Caebe Avatar answered Oct 05 '22 07:10

Keifer Caebe