0% found this document useful (0 votes)
9 views

Unlocking the Power of Angular Routing

The document discusses the importance of routing in Angular for building Single Page Applications (SPAs), highlighting features such as route guards, lazy loading, and dynamic parameters. Route guards secure access to routes, lazy loading improves performance by loading modules only when needed, and dynamic parameters allow for personalized URLs. The document provides examples of implementing these features in Angular applications.

Uploaded by

suresh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Unlocking the Power of Angular Routing

The document discusses the importance of routing in Angular for building Single Page Applications (SPAs), highlighting features such as route guards, lazy loading, and dynamic parameters. Route guards secure access to routes, lazy loading improves performance by loading modules only when needed, and dynamic parameters allow for personalized URLs. The document provides examples of implementing these features in Angular applications.

Uploaded by

suresh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

🌟

Notes: 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!

1. Route Guards: Securing Your Routes

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.

Example: Using CanActivate Guard

Guard Service:
import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';

@Injectable({ providedIn: 'root' })


export class AuthGuard implements CanActivate {
constructor(private router: 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';

const routes: Routes = [


{ path: 'dashboard', component: DashboardComponent, canActivate:
[AuthGuard] },
];

@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule],
})
export class AppRoutingModule {}

2. Lazy Loading: Boosting Performance


Lazy loading loads modules only when they’re needed, reducing the initial load
time and improving performance. This is especially useful for large applications.

Example: Setting Up Lazy Loading

Create a Module: ng generate module feature --route feature --module


app.module

Lazy Load the Module: const routes: Routes = [


{ path: 'feature', loadChildren: () => import('./feature/feature.module').then(m =>
m.FeatureModule) },
];

Angular automatically configures lazy loading and handles the dynamic loading of
the module.

3. Dynamic Parameters: Creating Dynamic Routes

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

Set Up the Route:

const routes: Routes = [


{ path: 'user/:id', component: UserDetailsComponent },
];

Access the Parameter in the Component:


import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

@Component({
selector: 'app-user-details',
template: `<p>User ID: {{ userId }}</p>`,
})
export class UserDetailsComponent implements OnInit {
userId!: string;

constructor(private route: ActivatedRoute) {}

ngOnInit(): void {
this.userId = this.route.snapshot.paramMap.get('id')!;
}
}

This setup ensures you can dynamically load data based on the route parameter.

Choosing the Right Feature

● Use route guards to secure sensitive pages.


● Implement lazy loading to optimize app performance.
● Leverage dynamic parameters for personalized or data-driven routes.

You might also like