Advanced Routing Techniques in Angular
1. Introduction
In Angular, routing is essential for creating single-page applications (SPAs). Advanced routing techniques enhance user experience and application performance by managing navigation effectively.
2. Route Parameters
Route parameters allow you to pass dynamic values in routes. For example, you can use a user ID in a route to fetch user details.
const routes: Routes = [
{ path: 'user/:id', component: UserComponent }
];
To retrieve the parameter in the component:
import { ActivatedRoute } from '@angular/router';
constructor(private route: ActivatedRoute) { }
ngOnInit() {
this.route.params.subscribe(params => {
const id = params['id'];
// Use the id to fetch user details
});
}
3. Nested Routes
Nested routes let you create a hierarchy of components. This is useful for displaying related views.
const routes: Routes = [
{ path: 'products', component: ProductsComponent, children: [
{ path: 'details/:id', component: ProductDetailsComponent },
{ path: 'reviews', component: ProductReviewsComponent }
]}
];
In this example, ProductDetailsComponent
and ProductReviewsComponent
are displayed within ProductsComponent
.
4. Route Guards
Route guards protect routes from unauthorized access. You can implement guards such as CanActivate
or CanDeactivate
.
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
constructor(private router: Router) {}
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): boolean {
const isLoggedIn = false; // Replace with actual authentication check
if (!isLoggedIn) {
this.router.navigate(['/login']);
return false;
}
return true;
}
}
Use the guard in routes:
const routes: Routes = [
{ path: 'protected', component: ProtectedComponent, canActivate: [AuthGuard] }
];
5. Lazy Loading
Lazy loading optimizes loading times by loading feature modules only when needed. This improves initial load performance.
Set up lazy loading in your routing module:
const routes: Routes = [
{ path: 'feature', loadChildren: () => import('./feature/feature.module').then(m => m.FeatureModule) }
];
Create a separate module for the feature, and define its routes.
FAQ
What are route parameters?
Route parameters are dynamic segments in your route that allow you to capture values from the URL, such as user IDs or product IDs.
How does lazy loading work?
Lazy loading allows you to load feature modules on demand, reducing the initial load time of your application.
What are route guards used for?
Route guards are used to control access to certain routes based on conditions such as user authentication.