Write code to implement an Auth Guard for route protection

0 votes
Can i Write code to implement an Auth Guard for route protection.
Feb 24, 2025 in Angular by Nidhi
• 16,260 points
457 views

1 answer to this question.

0 votes

An AuthGuard prevents unauthorized users from accessing specific routes. It uses Angular’s Route Guards to check authentication before navigating.

Step 1: Create an AuthGuard

import { Injectable } from '@angular/core';

import { CanActivate, Router } from '@angular/router';

import { AuthService } from './auth.service';

@Injectable({

  providedIn: 'root'

})

export class AuthGuard implements CanActivate {

  constructor(private authService: AuthService, private router: Router) {}

  canActivate(): boolean {

    if (this.authService.isLoggedIn()) {

      return true; // Allow navigation if authenticated

    }

    this.router.navigate(['/login']); // Redirect to login if not authenticated

    return false;

  }

}

Step 2: Implement AuthService

@Injectable({

  providedIn: 'root'

})

export class AuthService {

  isLoggedIn(): boolean {

    return !!localStorage.getItem('token'); // Example: Check if token exists

  }

}

Step 3: Apply AuthGuard in Routing Module

import { NgModule } from '@angular/core';

import { RouterModule, Routes } from '@angular/router';

import { DashboardComponent } from './dashboard.component';

import { LoginComponent } from './login.component';

import { AuthGuard } from './auth.guard';

const routes: Routes = [

  { path: 'dashboard', component: DashboardComponent, canActivate: [AuthGuard] },

  { path: 'login', component: LoginComponent },

];

@NgModule({

  imports: [RouterModule.forRoot(routes)],

  exports: [RouterModule]

})

export class AppRoutingModule {}

answered Feb 24, 2025 by Navya

Related Questions In Angular

0 votes
1 answer

How can we redirect to an existing route using ngRoute?

Routing is just another way of fixing some content ...READ MORE

answered Feb 6, 2020 in Angular by Niroj
• 82,800 points
4,475 views
0 votes
2 answers

How to detect a route change in Angular?

Hii Kartik For Angular 7 someone should write like: this.router.events.subscribe((event: Event) ...READ MORE

answered Apr 22, 2020 in Angular by Niroj
• 82,800 points
30,764 views
0 votes
1 answer

How to set focus on an input field after rendering?

Hello @kartik, You should do it in componentDidMount and refs callback instead. ...READ MORE

answered Jul 22, 2020 in Angular by Niroj
• 82,800 points
2,716 views
0 votes
1 answer

Should I use map or switchmap when using angular http module?

When working with the Angular HTTP module, ...READ MORE

answered Feb 24, 2025 in Angular by Navya
552 views
0 votes
1 answer

How does BehaviorSubject differ from Subject in state management?

Feature Subject BehaviorSubject Initial Value No initial value Requires an initial value Last ...READ MORE

answered Feb 24, 2025 in Node-js by Navya
575 views
0 votes
1 answer

How can you implement forkJoin for multiple API responses aggregation?

In Angular, forkJoin is used to combine ...READ MORE

answered Feb 24, 2025 in Node-js by Navya
648 views
0 votes
1 answer

What is the use of takeUntil to cancel a subscription?

takeUntil is an RxJS operator used to ...READ MORE

answered Feb 24, 2025 in Node-js by Navya
682 views
0 votes
1 answer

How to send multipart/form-data for a file upload in Angular?

In Angular, you can send files using ...READ MORE

answered Feb 24, 2025 in Angular by Navya
830 views
0 votes
1 answer

How to build an Angular project?

To build an Angular project, follow these ...READ MORE

answered Feb 25, 2025 in Angular by Navya
573 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP