In this tutorial, we will be discussing how to implement user access on routing in an Angular 14 application using guards. Guards are used to restrict access to certain routes based on certain conditions. This can be useful for protecting sensitive information or requiring a user to be logged in to access certain features of your app.
Prerequisites
Before we begin, make sure you have the following installed:
- Node.js
- Angular CLI 14
Step 1: Create a new Angular 14 application
To create a new Angular 14 application, open the command prompt and run the following command:
ng new myApp
This will create a new Angular 14 application with the name “myApp” in a new directory.
Step 2: Create an Auth Service
To create an Auth Service, open the command prompt and navigate to the root of your Angular 14 application. Run the following command:
ng g service services/auth
This will create a new Auth Service in the “src/app/services” directory.
Step 3: Create an Auth Guard
To create an Auth Guard, open the command prompt and navigate to the root of your Angular 14 application. Run the following command:
ng g guard guards/auth
This will create a new Auth Guard in the “src/app/guards” directory.
Step 4: Implement Auth Service
Open the “src/app/services/auth.service.ts” file and implement the Auth Service. In this example, we will be using a simple isLoggedIn variable to keep track of the user’s authentication status.
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class AuthService {
isLoggedIn: boolean = false;
login() {
this.isLoggedIn = true;
}
logout() {
this.isLoggedIn = false;
}
}
Step 5: Implement Auth Guard
Open the “src/app/guards/auth.guard.ts” file and import the Auth Service. Implement the Auth Guard by using the canActivate() method and check the user’s authentication status before allowing access to the route.
import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
import { AuthService } from '../services/auth.service';
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
constructor(private auth: AuthService, private router: Router) {}
canActivate(): boolean {
if (!this.auth.isLoggedIn) {
this.router.navigate(['/login']);
return false;
}
return true;
}
}
Step 6: Add Auth Guard to Router
Open the “src/app/app-routing.module.ts” file and import the Auth Guard. Add the Auth Guard to the routes to which you want to restrict access.
import { AuthGuard } from './guards/auth.guard';
const routes: Routes = [
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{ path: 'home', component: HomeComponent },
{ path: 'restricted', component: RestrictedComponent, canActivate: [AuthGuard] },
{ path: 'login', component: LoginComponent },
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
In this example, we have added the Auth Guard to the “restricted” route, which means that the user will only be able to access this page if they are logged in.
Step 7: Add Login and Logout functionality
To add login and logout functionality, you can add buttons to your login and restricted pages that call the login() and logout() methods of the Auth Service respectively.
<button (click)="auth.login()">Login</button>
<button (click)="auth.logout()">Logout</button>
Step 8: Test the App
To test the app, run the following command:
ng serve
You should now be able to navigate to the “home” and “login” pages without any restrictions, but when you try to access the “restricted” page, you will be redirected to the “login” page if you are not logged in.
Other Uses
Guards can also be used in combination with other types of guards such as Role-based access control or CanDeactivate to create more advanced access control mechanisms in your application.
Conclusion
In this tutorial, we have discussed how to implement user access on routing in an Angular 14 application using guards. We have shown how to create an Auth Service and Auth Guard, and how to use them to restrict access to certain routes based on user authentication status. This can be a useful tool for protecting sensitive information or requiring a user to be logged in to access certain features of your app.
Leave a Reply