Usually when you need to navigate between routes in Angular, you will want to load those components. The problem is that often, you don’t want data ready before the component is displayed. Angular Resolvers can be used in that case!
The Angular Resolver is a service that pre-fetches data into the route. It helps the data it needs once the component loads to avoid an empty state, or a loading spinner.
import { Injectable } from '@angular/core';
import { Resolve } from '@angular/router';
import { Observable } from 'rxjs';
import { DataService } from './data.service';
@Injectable({ providedIn: 'root' })
export class DataResolver implements Resolve<any> {
constructor(private dataService: DataService) {}
resolve(): Observable<any> {
return this.dataService.getData();
}
}
const routes: Routes = [
{
path: 'details/:id',
component: DetailsComponent,
resolve: { data: DataResolver }
}
];
export class DetailsComponent implements OnInit {
data: any;
constructor(private route: ActivatedRoute) {}
ngOnInit() {
this.data = this.route.snapshot.data['data'];
}
}
Angular Resolvers are one of the most powerful ones for pre-fetching data before navigating to a route. It guarantees a cleaner components which is smoother for the user.
Ready to transform your business with our technology solutions? Contact Us today to Leverage Our Angular Expertise.
Contact Us