Angular 6 — Login and Router Tutorial

Özgür GÜL
Jul 21, 2018 · 2 min read

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.

Preparing

Our login page and its component:

You are seeing ApiService, CustomerService, and Router injected from the constructor. Let's describe them:

ApiService:

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

CustomerService:

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.

Router:

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:

Image for post

And then when he logged in, it will be redirected to /dashboard:

Image for post

Conclusion

You can access the source code of this example from below:


Shameless plug: follow me on twitter and check my new project Landly (a landing page generator). Also I promise I will start tweeting. :)

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store