Angular Route Guard – CanMatch
In this Angular tutorial, we will learn about the concept of route guarding and how to implement it using the CanMatch interface in Angular. Route guarding is a critical feature in modern web applications to restrict access to certain routes based on authentication and authorization rules.
What is CanMatch in Angular?
CanMatch is an interface in Angular that is used to define a guard for a route. It contains a single method named `canActivate`, which is responsible for determining whether a route can be activated or not. The `canActivate` method returns a boolean value or a promise or an observable that resolves to a boolean value.
Implementing Route Guard Using CanMatch
To implement route guarding using CanMatch, we need to create a service that implements the CanMatch interface and then use that service as a route guard for specific routes in our application. Here’s an example of how to achieve this:
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree } from '@angular/router';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable | Promise | boolean | UrlTree {
// Check if the user is authenticated
if (/* user is authenticated */) {
return true;
} else {
// Redirect to login page or show an error message
return false;
}
}
}
Using the Route Guard in Angular
Once we have created our route guard service, we can use it to protect specific routes in our application. We can do this by adding the `canActivate` property to the route definition in our routing module and specifying the route guard service as its value. Here’s an example:
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { ProfileComponent } from './profile/profile.component';
import { AuthGuard } from './auth.guard';
const routes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'profile', component: ProfileComponent, canActivate: [AuthGuard] }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
Conclusion
Route guarding is an essential feature in Angular applications to ensure that certain routes are only accessible by authenticated users. By using the CanMatch interface and implementing route guard services, we can easily enforce authentication and authorization rules for our application’s routes.
Very Useful tutorial. tnx for your explanation