Angular 6 — Login and Router Tutorial
In Angular 6 when you want to create a web application that has login functionality, you probably will want to have protected routes too.
To have protected routes, we have to implement CanActivate interface to create some kind of guard mechanism.
Our login page and it’s component:
You are seeing ApiService, CustomerService and Router injected from constructor. Lets describe them:
For this tutorial’s login functionality, I used a free dummy API web service named ReqRes. ApiService class injects HttpClient and provides me a login() method so I can call this method from anywhere of the application. It returns an Observable<LoginResultModel>.
This class sets the given token to preferred storage (for this tutorial I used localStorage) and has a isLogged() method, so we can check if our customer is logged already. Putting this logic in this small class improves the readability of code, because we know where our customer related methods belong.
After successful login() call, we call navigateByUrl() method provided by Router. It redirects to given route.
Connecting with Router
As I said, to connect our custom protect logic with Router, we have to create a guard mechanism. Angular Router provides us CanActivate interface that can return an Observable<boolean>, Promise<boolean> or boolean.
I simply created a NeedAuthGuard. It returns true if our customer is logged, so Angular Router can continue invoke our component.
Below next line, If our customer is not logged, we are redirecting him to /login page with current route showing as redirectUrl in query params.
To connect our NeedAuthGuard, we have to attach this class to our Router instance:
Thats it, whenever a user opens the /dashboard route, it will redirected to /login page if he is not logged in:
And then we he logged in, it will be redirected to /dashboard:
You can access the source code of this example from below: