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 its component:
You are seeing ApiService, CustomerService, and Router injected from the constructor. Let's 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 an 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 a 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 to invoke our component.
Below the next line, If our customer is not logged, we are redirecting him to /login page with the current route showing as redirectUrl in query params.
To connect our NeedAuthGuard, we have to attach this class to our Router instance:
That's it, whenever a user opens the /dashboard route, he will be redirected to /login page if he is not logged in:
And then when he logged in, it will be redirected to /dashboard:
You can access the source code of this example from below: