Unlocking the Power of Angular Routing
Unlocking the Power of Angular Routing
Routing is at the heart of building Single Page Applications (SPAs) with Angular,
allowing smooth navigation between views. Beyond basic routing, Angular offers
advanced features like route guards, lazy loading, and dynamic parameters to
make your applications more scalable, secure, and performant. Let’s dive into
these features!
Route guards ensure that only authorized users can access specific routes in your
application. Angular provides multiple types of guards:
● CanActivate: Prevents unauthorized access to a route.
● CanDeactivate: Prompts the user when they navigate away with unsaved
changes.
● Resolve: Fetches data before navigating to a route.
Guard Service:
import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
canActivate(): boolean {
const isAuthenticated = !!localStorage.getItem('token'); // Example logic
if (!isAuthenticated) {
this.router.navigate(['/login']);
}
return isAuthenticated;
}
}
Apply the Guard to a Route:
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { DashboardComponent } from './dashboard/dashboard.component';
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule],
})
export class AppRoutingModule {}
Angular automatically configures lazy loading and handles the dynamic loading of
the module.
Dynamic parameters let you pass data like IDs or usernames in the URL. This is
useful for pages like user profiles or product details.
Example: Using Dynamic Parameters
@Component({
selector: 'app-user-details',
template: `<p>User ID: {{ userId }}</p>`,
})
export class UserDetailsComponent implements OnInit {
userId!: string;
ngOnInit(): void {
this.userId = this.route.snapshot.paramMap.get('id')!;
}
}
This setup ensures you can dynamically load data based on the route parameter.