Resolve Guard in Angular
The Resolve
guard in Angular is used to pre-fetch data before navigating to a route. This tutorial covers the basics of setting up and using the Resolve
guard effectively in your Angular applications.
Setting Up Resolve Guard
To set up the Resolve
guard, you need to create a resolver service and implement the Resolve
interface:
// app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouterModule, Routes } from '@angular/router';
import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';
import { UserComponent } from './user/user.component';
import { UserResolver } from './user.resolver';
import { UserService } from './user.service';
const routes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'user/:id', component: UserComponent, resolve: { user: UserResolver } }
];
@NgModule({
declarations: [AppComponent, HomeComponent, UserComponent],
imports: [BrowserModule, RouterModule.forRoot(routes)],
providers: [UserResolver, UserService],
bootstrap: [AppComponent]
})
export class AppModule { }
// user.resolver.ts
import { Injectable } from '@angular/core';
import { Resolve, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Observable } from 'rxjs';
import { UserService } from './user.service';
@Injectable({
providedIn: 'root'
})
export class UserResolver implements Resolve {
constructor(private userService: UserService) {}
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable {
const userId = route.paramMap.get('id');
return this.userService.getUser(userId);
}
}
// user.service.ts
import { Injectable } from '@angular/core';
import { Observable, of } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class UserService {
getUser(id: string): Observable {
// Replace with actual HTTP request
return of({ id, name: 'User ' + id });
}
}
// home.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-home',
template: 'Home Component
',
})
export class HomeComponent { }
// user.component.ts
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-user',
template: 'User Component
User: {{ user | json }}
',
})
export class UserComponent implements OnInit {
user: any;
constructor(private route: ActivatedRoute) {}
ngOnInit() {
this.user = this.route.snapshot.data['user'];
}
}
// app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent { }
// app.component.html
Creating a Resolver Service
Create a resolver service using the Angular CLI command ng generate service user
and implement the Resolve
interface:
// user.resolver.ts
import { Injectable } from '@angular/core';
import { Resolve, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Observable } from 'rxjs';
import { UserService } from './user.service';
@Injectable({
providedIn: 'root'
})
export class UserResolver implements Resolve {
constructor(private userService: UserService) {}
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable {
const userId = route.paramMap.get('id');
return this.userService.getUser(userId);
}
}
Using the Resolve Guard
Use the resolve
property in your route configuration to specify the resolver:
// app.module.ts
const routes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'user/:id', component: UserComponent, resolve: { user: UserResolver } }
];
Key Points
- The
Resolve
guard is used to pre-fetch data before navigating to a route in Angular applications. - Create a resolver service and implement the
Resolve
interface. - Use the
resolve
property in your route configuration to specify the resolver. - Access the resolved data in your component using the
ActivatedRoute
service.
Conclusion
The Resolve
guard in Angular provides a powerful way to pre-fetch data before navigating to a route. By understanding and using the Resolve
guard effectively, you can create efficient and user-friendly applications with pre-fetched data. Happy coding!