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 in Angular by Nidhi
• 10,400 points
27 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 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,840 points
3,924 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,840 points
29,472 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,840 points
2,102 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 in Angular by Navya
32 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 in Node-js by Navya
31 views
0 votes
1 answer
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 in Node-js by Navya
40 views
0 votes
1 answer
0 votes
1 answer

How to build an Angular project?

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

answered 6 days ago in Angular by Navya
35 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