Angular data resolvers
Angular resolvers can be used to pre-fetch data during navigation (before the route is finally activated) and pass it to component.
It's worth mentioning that resolvers are executed after all defined guards succeeded.
In following example we define example route with data resolver. The target component will be activated once the data has been resolved (after 5s delay).
const exampleResolver: ResolveFn<string> = (route: ActivatedRouteSnapshot, state: RouterStateSnapshot) => {
return of('Hello').pipe(delay(5000));
};
const routes: Routes = [
{
path: 'example',
component: ExampleComponent,
resolve: {resolverData: exampleResolver}
}
];
To access resolved data just use ActivatedRoute
.
@Component({
//...
})
export class ExampleComponent {
constructor(private activatedRoute: ActivatedRoute) {}
ngOnInit() {
this.activatedRoute.data.subscribe(({resolverData}) => console.log(resolverData)); //Hello
}
}