What is Route Resolver in Angular: Explanation and Example
route resolver in Angular is a service that fetches data before a route is activated, ensuring the component has the data it needs when it loads. It runs during navigation and delays the route until the data is ready.How It Works
Think of a route resolver like a helpful assistant who prepares everything before you enter a room. When you navigate to a page in Angular, the resolver fetches the necessary data first, so the page doesn't show empty or loading states.
This happens because Angular waits for the resolver to finish its job before activating the route and displaying the component. This way, the component starts with all the data it needs, making the user experience smoother and faster.
Example
This example shows a simple resolver that fetches user data before loading the UserComponent.
import { Injectable } from '@angular/core'; import { Resolve, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router'; import { Observable, of } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class UserResolver implements Resolve<string> { resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<string> { // Simulate fetching user data return of('User data loaded'); } } // In your routing module import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { UserComponent } from './user.component'; const routes: Routes = [ { path: 'user', component: UserComponent, resolve: { userData: UserResolver } } ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule {} // In UserComponent import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; @Component({ selector: 'app-user', template: '<p>{{ data }}</p>' }) export class UserComponent implements OnInit { data: string | undefined; constructor(private route: ActivatedRoute) {} ngOnInit() { this.data = this.route.snapshot.data['userData']; } }
When to Use
Use a route resolver when you want to load data before showing a page, so the user sees a fully ready screen without waiting or seeing loading spinners inside the component.
Common cases include loading user profiles, product details, or any data that the page depends on to display correctly. This improves user experience by avoiding flickers or incomplete views.
Key Points
- A route resolver fetches data before route activation.
- Angular waits for the resolver to complete before loading the component.
- Resolvers help avoid loading states inside components.
- They improve user experience by showing ready content immediately.