How to use AuthGuard in angular 5

reactive form

AuthGuard is an interesting feature of angular. If you want to apply AuthGuard on routes then this the best option angular has given. It always returns either true or false depends on guard condition you applied.

There are five different types of guards and each of them is called in a particular sequence. The router’s behavior is modified differently depending on which guard is used. The guards are:

  • CanActivate
  • CanActivateChild
  • CanDeactivate
  • CanLoad
  • Resolve

In this tutorial, I am going to use Angular CLI. If you are new to CLI then you can check my previous blog Angular CLI.

Creating Guard Service

To create guard service, here I am going to use CLI commands. Run the below command to create auth guard service.



After successful execution of the command, you will find two files in your services folder that is auth-guard.service.ts and auth-guard.service.spec.ts.

auth-guard.service.ts

In guard service, you need to implement a CanActivate interface to access canActivate method.
Now create one more service to set and get user data for authentication.

It will generate two more files in your services folder that is auth.service.ts and auth.service.spec.ts.

auth.service.ts

Above service will take user data after successful login and will store in browser localStorage. There is four functions available in this service.

  • setToken()
  • getToken()
  • isLoggednIn()
  • logout()

Create one component to handle login.

login.component.ts


login.component.html

In this example, I have used Reactive Form

Applying Auth Guard on routes

Here canActivate call AuthGuardService for every route. And every time AuthGuardService will check in Browser localStorage that user info is stored or not.
If user data in not stored in localStorage that AuthGuardService will redirect you to the login page again.



Please follow and like us:

You May Also Like

About the Author: Sujeet Kumar

Sujeet is Web and Android Devloper with a soft spot for functional programming. I like to play cricket, regular workout.

Leave a Reply

Your email address will not be published. Required fields are marked *