Basic routing allows users to navigate between components.
However, large enterprise applications need more advanced controls.
You need to optimize loading times, secure specific pages, and fetch data before a page renders!
By default, Angular bundles your entire application into a single JavaScript file.
For massive applications, this results in agonizingly slow initial load times.
To fix this, you use Lazy Loading (loadChildren or loadComponent), which forces Angular to only download the code for a route when the user actually navigates to it!
const routes: Routes = [
// The AdminComponent code won't be downloaded until the user visits '/admin'
{
path: 'admin',
loadComponent: () => import('./admin/admin.component').then(m => m.AdminComponent)
}
];
Often, you need to protect certain routes (like an Admin dashboard) from unauthorized users.
Angular provides Route Guards to intercept a navigation attempt and either allow or deny it.
In modern Angular, you define a guard as a simple functional canActivateFn.
// The Guard Function
export const authGuard: CanActivateFn = () => {
const isLoggedIn = checkUserLoginStatus();
return isLoggedIn ? true : false; // If false, navigation is cancelled
};
// Applying the guard in the routes array
const routes: Routes = [
{ path: 'dashboard', component: DashboardComponent, canActivate: [authGuard] }
];
Sometimes a component requires API data to display correctly.
Instead of loading an empty component and showing a loading spinner, you can use a Route Resolver.
A Resolver fetches the API data before the navigation finishes, passing the data directly into the newly loaded component!
What is the primary benefit of configuring Lazy Loading (loadComponent) in your routes?
If you want to completely block unauthenticated users from viewing a specific route, what feature should you use?