Implementing Guard In Angular 5 App

In this post, we are going to implement Guard, which helps us to restrict users to access some pages if they haven’t logged in to our application, in Angular 5.

Introduction

This post is a continuation of the course Developing an Angular 5 App series. If you haven’t gone through the previous posts yet, I strongly recommend you do that. You can find the links to the previous posts below. In this post, we are going to implement Guard, which helps us to restrict users to access some pages if they haven’t logged in to our application in Angular 5. So, by the end of this article, you will learn how you can handle unauthorized route accesses. I hope you will like this article.

You can always see this article on my blog here: http://sibeeshpassion.com/implementing-guard-in-angular-5-app/

Developing an Angular 5 App series

These are the previous posts in this series. Please go ahead and have a look.

  1. What Is New and How to Set Up our First Angular 5 Application
  2. Angular 5 Basic Demo Project Overview
  3. Generating Your First Components And Modules in Angular 5 App
  4. Implement Validations in Angular 5 App
  5. Implementing Guard in Angular 5 App

Source Code

You can always clone or download the source code here.

Background

We may have many numbers of pages on our app, some may be used by logged in users, and some can be used by unauthorized users. But if you are letting all the users use all the pages, no matter whether they have logged in or not, obviously that’s not a perfect application. In our application, we are going to make our homepage available only for a logged in user. To do this, we can use Guard.

Generate Guard

As we are using Angular CLI, we can easily generate Auth Guard on our application. Do you remember that we have created some components in our previous article? We can always create a Guard in the same way.

  1. PS F:\Visual Studio\ng5> ng generate guard auth

In the above step, we are generating guard on our root level. Once you run the above command, this will generate two new Typescript files as follows.

Angular

Let’s go to those two files now.

auth.guard.ts

  1. import {  
  2.     Injectable  
  3. } from '@angular/core';  
  4. import {  
  5.     CanActivate,  
  6.     ActivatedRouteSnapshot,  
  7.     RouterStateSnapshot  
  8. } from '@angular/router';  
  9. import {  
  10.     Observable  
  11. } from 'rxjs/Observable';  
  12. @Injectable()  
  13. export class AuthGuard implements CanActivate {  
  14.     canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable < boolean > | Promise < boolean > | boolean {  
  15.         return true;  
  16.     }  

auth.guard.spec.ts

  1. import {  
  2.     TestBed,  
  3.     async,  
  4.     inject  
  5. } from '@angular/core/testing';  
  6. import {  
  7.     AuthGuard  
  8. } from './auth.guard';  
  9. describe('AuthGuard', () => {  
  10.     beforeEach(() => {  
  11.         TestBed.configureTestingModule({  
  12.             providers: [AuthGuard]  
  13.         });  
  14.     });  
  15.     it('should ...', inject([AuthGuard], (guard: AuthGuard) => {  
  16.         expect(guard).toBeTruthy();  
  17.     }));  
  18. });  

This is just a test file, we can see how to perform tests on the Angular app in another article. Let’s concentrate on the implementation for now.

Generate login component and set up

Now, that we have Guard ready for modification,, let’s create a component for login.

  1. PS F:\Visual Studio\ng5> ng g c login
  2. create src/app/login/login.component.html (24 bytes)
  3. create src/app/login/login.component.spec.ts (621 bytes)
  4. create src/app/login/login.component.ts (265 bytes)
  5. create src/app/login/login.component.css (0 bytes)
  6. update src/app/app.module.ts (1331 bytes)
  7. PS F:\Visual Studio\ng5>

Now, it is time to edit our routes in app.module.ts with the new route for login. Please note that it is not a recommended way to create routes in app.module.ts file. We should create a separate routing module for the same and use it in app.module.ts. I will be sharing how to do that in another article.

  1. import {  
  2.     LoginComponent  
  3. } from './login/login.component';  
  4. const myRoots: Routes = [{  
  5.     path: '',  
  6.     component: HomeComponent,  
  7.     pathMatch: 'full'  
  8. }, {  
  9.     path: 'register',  
  10.     component: RegistrationComponent  
  11. }, {  
  12.     path: 'login',  
  13.     component: LoginComponent  
  14. }, {  
  15.     path: 'home',  
  16.     component: HomeComponent  
  17. }]  
  18. @NgModule({  
  19.     declarations: [  
  20.         AppComponent,  
  21.         HomeComponent,  
  22.         NavComponent,  
  23.         RegistrationComponent,  
  24.         LoginComponent  
  25.     ],  
  26.     imports: [  
  27.         BrowserModule, BrowserAnimationsModule, FormsModule, ReactiveFormsModule,  
  28.         MatButtonModule, MatCardModule, MatInputModule, MatSnackBarModule, MatToolbarModule,  
  29.         RouterModule.forRoot(myRoots)  
  30.     ],  
  31.     providers: [],  
  32.     bootstrap: [AppComponent]  
  33. })  

We may also need to edit the nav.component.html by adding a new button for login.

  1. <mat-toolbar color="primary">  
  2.    <button mat-button routerLink="/">Home</button>  
  3.    <button mat-button routerLink="/register">Register</button>  
  4.    <button mat-button routerLink="/login">Login</button>  
  5. </mat-toolbar>  

Now, go to your login.component.html file and add the following markup.

  1. <mat-card>  
  2.     <form [formGroup]="form" (ngSubmit)="login()">  
  3.         <mat-input-container> <input matInput type="email" placeholder="Email" formControlName="email" /> </mat-input-container>  
  4.         <mat-input-container> <input matInput type="password" placeholder="Password" formControlName="password" /> </mat-input-container> <button mat-raised-button type="submit" color="primary">Login</button> </form>  
  5. </mat-card>  

As you can see, we are actually calling a login method on submit. Before we implement that function now on login.component.ts file let’s create an auth service and edit it as we did before. 

  1. import {  
  2.     Injectable  
  3. } from '@angular/core';  
  4. import {  
  5.     Router  
  6. } from '@angular/router';  
  7. @Injectable()  
  8. export class AuthService {  
  9.     constructor(private myRoute: Router) {}  
  10.     sendToken(token: string) {  
  11.         localStorage.setItem("LoggedInUser", token)  
  12.     }  
  13.     getToken() {  
  14.         return localStorage.getItem("LoggedInUser")  
  15.     }  
  16.     isLoggednIn() {  
  17.         return this.getToken() !== null;  
  18.     }  
  19.     logout() {  
  20.         localStorage.removeItem("LoggedInUser");  
  21.         this.myRoute.navigate(["login"]);  
  22.     }  
  23. }  

Now, it is time to edit our login.component.ts file.

  1. import {  
  2.     Component,  
  3.     OnInit  
  4. } from '@angular/core';  
  5. import {  
  6.     FormBuilder,  
  7.     Validators  
  8. } from '@angular/forms';  
  9. import {  
  10.     Router  
  11. } from '@angular/router';  
  12. import {  
  13.     AuthService  
  14. } from '../auth.service';  
  15. @Component({  
  16.     selector: 'app-login',  
  17.     templateUrl: './login.component.html',  
  18.     styleUrls: ['./login.component.css']  
  19. })  
  20. export class LoginComponent implements OnInit {  
  21.     form;  
  22.     constructor(private fb: FormBuilder, private myRoute: Router, private auth: AuthService) {  
  23.         this.form = fb.group({  
  24.             email: ['', [Validators.required, Validators.email]],  
  25.             password: ['', Validators.required]  
  26.         });  
  27.     }  
  28.     ngOnInit() {}  
  29.     login() {  
  30.         if (this.form.valid) {  
  31.             this.auth.sendToken(this.form.value.email)  
  32.             this.myRoute.navigate(["home"]);  
  33.         }  
  34.     }  
This is not the preferred way of doing this, instead, you should create an API service and connect to a database. And then, check whether this email and password are valid or not, at last, you should set the localStorage with the token you get from server API. This topic is enough for another article, to make this article short, I am just setting the value email here.

If you are getting an error as “ERROR Error: Uncaught (in promise): EmptyError: no elements in sequence”, please make sure that you have rxjs version greater than or equal to 5.5.4 in a package.json file. The rxjs version 5.5.3 has this issue with Angular 5.

Now, run your application and make sure that it is redirecting to the homepage. You can also check the localStorage entry on your browser console.

Angular

Set up Guard 

Let’s go to our auth.guard.ts file and make some changes.

  1. import {  
  2.     Injectable  
  3. } from '@angular/core';  
  4. import {  
  5.     CanActivate,  
  6.     ActivatedRouteSnapshot,  
  7.     RouterStateSnapshot  
  8. } from '@angular/router';  
  9. import {  
  10.     Observable  
  11. } from 'rxjs/Observable';  
  12. import {  
  13.     AuthService  
  14. } from './auth.service';  
  15. import {  
  16.     Router  
  17. } from '@angular/router';  
  18. @Injectable()  
  19. export class AuthGuard implements CanActivate {  
  20.     constructor(private auth: AuthService, private myRoute: Router) {}  
  21.     canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable < boolean > | Promise < boolean > | boolean {  
  22.         if (this.auth.isLoggednIn()) {  
  23.             return true;  
  24.         } else {  
  25.             this.myRoute.navigate(["login"]);  
  26.             return false;  
  27.         }  
  28.     }  

Do not forget to add AuthService and AuthGuard in providers in app.module.ts.

  1. import { AuthService } from './auth.service';  
  2. import { AuthGuard } from './auth.guard';  

Use Auth Guard in Routes

Wow, the set up is done, now it is time for action. Let’s go to our routes now and change the code as before. 

  1. const myRoots: Routes = [{  
  2.     path: '',  
  3.     component: HomeComponent,  
  4.     pathMatch: 'full',  
  5.     canActivate: [AuthGuard]  
  6. }, {  
  7.     path: 'register',  
  8.     component: RegistrationComponent  
  9. }, {  
  10.     path: 'login',  
  11.     component: LoginComponent  
  12. }, {  
  13.     path: 'home',  
  14.     component: HomeComponent,  
  15.     canActivate: [AuthGuard]  
  16. }];  
Run your application and try to access the home page before login. If everything goes fine, it should redirect you to the login page.
 
Angular

Let’s do some more coding on the nav.component.html and nav.component.ts for making our app more meaningful.

nav.component.ts

  1. import {  
  2.     Component,  
  3.     OnInit  
  4. } from '@angular/core';  
  5. import {  
  6.     AuthService  
  7. } from '../auth.service';  
  8. @Component({  
  9.     selector: 'app-nav',  
  10.     templateUrl: './nav.component.html',  
  11.     styleUrls: ['./nav.component.css']  
  12. })  
  13. export class NavComponent implements OnInit {  
  14.     constructor(private auth: AuthService) {}  
  15.     ngOnInit() {}  
  16. }  

nav.component.html

  1. <mat-toolbar color="primary">  
  2.    <button mat-button routerLink="/home">Home</button>  
  3.    <button mat-button *ngIf="!auth.isLoggednIn()" routerLink="/register">Register</button>  
  4.    <button mat-button *ngIf="!auth.isLoggednIn()" routerLink="/login">Login</button>  
  5.    <button mat-button *ngIf="auth.isLoggednIn()" (click)="auth.logout()">Logout</button>  
  6. </mat-toolbar> 
Here, we are just making the log out button available only for logged in users and hiding register and login button for logged in users. Sounds good? The auth.isLoggedIn function will be available on this page as we are injecting the auth service on our nav.component.ts file.

Conclusion

Thanks a lot for reading. Did I miss anything that you may think is needed? Did you find this post useful? I hope you liked this article. Please share with me your valuable suggestions and feedback.

Your turn. What do you think?

A blog isn’t a blog without comments, but do try to stay on topic. If you have a question unrelated to this post, you’re better off posting it on C# Corner, Code Project, Stack Overflow, Asp.Net Forum instead of commenting here. Tweet or email me a link to your question there and I’ll definitely try to help if I can.