Set up a simple Guard in Angular 12

Let’s say you want to add a Guard so that you force people to be logged in at certain pages or routes rather. I am using Angular 12 but you can do this is lower versions on Angular too!

Let us create a folder called services if you haven’t one already, and in it create a file you call guard.service.ts.

Inside it, set up your service like this:

import { Injectable } from "@angular/core";
import { ActivatedRoute, Router, ActivatedRouteSnapshot, RouterStateSnapshot } from "@angular/router";
import { Observable } from "rxjs";
import { tap, map } from "rxjs/operators";
import { AngularFireAuth } from '@angular/fire/auth';

@Injectable()
export class guardService {
    constructor(
        private route: ActivatedRoute,
        private router: Router,
        public af: AngularFireAuth) { }
    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
        return this.af.authState.pipe(
            map(auth => {
                if (auth === null || auth === undefined) {
                    this.router.navigate(['/login']); //Redirect if not authenticated
                    return false;
                } else {
                    return true;
                }
            })
        );
    }
}

As you can notice, we are using AngularFire here, you could easily change this up to whatever you use for authentication, but if you want to do it the AngularFire you like I’ve done, head over to the the AngularFire github page and set up your project there. What we do then is that we check whatever the user is logged in or logged out with the help of the authState method from AngularFireAuth. If auth is NULL, it means that the user is not logged in and we can use the ActivatedRouteSnapShot to navigate him or her to another page.

Then inside your app-routing-module.ts file with routes, adjust them to use this guard with the help of the canActivate property like this (see the first one, for the home page):

const routes: Routes = [{
  path: '', component: MainComponent,
  canActivate: [guardService]
}, 
];

So this means that whenever we visit the home page, like http://localhost:4200/ or whatever you domain is, you’ll go through the guardService we created first, and if we are logged in we should be OK, otherwise we’ll end up at the /login page.

Only one more thing to add is to add your guardService to @NgModule inside the app.module.ts file, under providers:

  providers: [
    guardService
  ],

Feel free to add a Component called login so that whenever we are not logged in you’ll go there:

ng g component login

And add it to your routes:

const routes: Routes = [{
  path: '', component: MainComponent,
  canActivate: [guardService]
}, 
{
  path: 'login', component: LoginComponent,
}, 
];

And there you have a simple Guard in Angular setup!

0 0 votes
Article rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments