In Angular 16, we can use a different approach.
We can create a resolver function
ng generate resolver my-resolver
Which will give us some template code for our resolver function, returning a ResolveFn from '@angular/router';. We can use this resolver function preload our component with data. Similarly to Sunny's answer. Create a resolve attribute in your routing module.
// routing module
{
path: 'book',
component: BookComponent,
resolve: {
pageData: myResolver
}
}
Then, implement the resolver, which will fetch the data you need to preload.
// myResolver.resolver.ts
export const myResolver: ResolveFn<Promise<any>> = (
route,
state,
myApiService: MyApiService = inject(MyApiService)
) => {
// assume we have a service to fetch our data.
// In this example, 'myApiService' has a function which returns the data we need.
// It returns a Promise, but your service might return an Observable (which is totally OK.)
return myApiService.getData(route.params['slug']);
};
Here's an example from Angular's documentation
Replaysubjects -> whenever You inject the services' in components => subscribe to the service's public prop (the Subject) => you have your data instantly, kinda ...resolversthere, ie. angular.io/api/router/Resolve. Enables you to preload any necessary data before navigating to a given route.