How to use Resolve guard in Angular
Resolve guards in Angular pre-load data before route activation, ensuring components receive required data immediately upon initialization. As the creator of CoreUI with extensive Angular experience since 2014, I’ve used Resolve guards in numerous dashboard applications to eliminate loading states and improve user experience. The most effective approach implements the Resolve interface to fetch data that components need before they’re displayed. This pattern prevents flickering loading states and ensures smooth navigation with pre-populated data.
Implement the Resolve interface to pre-load data before route activation and pass it to components.
import { Injectable } from '@angular/core'
import { Resolve, ActivatedRouteSnapshot } from '@angular/router'
import { Observable } from 'rxjs'
import { UserService } from './user.service'
@Injectable({
providedIn: 'root'
})
export class UserResolve implements Resolve<any> {
constructor(private userService: UserService) {}
resolve(route: ActivatedRouteSnapshot): Observable<any> {
const userId = route.paramMap.get('id')
return this.userService.getUser(userId)
}
}
// In component
export class UserDetailComponent implements OnInit {
user: any
constructor(private route: ActivatedRoute) {}
ngOnInit() {
this.user = this.route.snapshot.data['user']
}
}
// In routing configuration
{
path: 'user/:id',
component: UserDetailComponent,
resolve: {
user: UserResolve
}
}
This code creates a Resolve guard that fetches user data using the ID from route parameters before the component loads. The resolved data is available in the component’s route data, eliminating the need for loading states. The router waits for the resolve function to complete before activating the route and instantiating the component.
Best Practice Note:
This is the data pre-loading pattern we use in CoreUI Angular components for seamless user experience in enterprise applications. Resolve guards should handle errors gracefully and consider implementing timeouts for slow API responses to prevent indefinite loading states.



