Resolvers in Angular
unleash the power of routing -Part-1
This article will help you when you want to load data at the initialization of a component
For example
I have a data related to a User like the user’s preferred address of delivery that I want to load during a checkout.
For this scenario, I am having the checkout details in a component named checkoutComponent and all the userDetails with a API call which is there in my service class named UserService.ts . When the user routes to the checkout page,the details related to the user has to be preloaded. Inorder to achieve it, We have to create a router resolver that will help us to complete the job.
The Following are the steps to create a Router resolver
Step 1:
Create a Service File named Preload.resolver.ts
@Injectable()
export class PreloadResolver implements Resolve<any> {constructor(private userService: UserService) { }
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<any>
{
return this.userService.getUserDetails().first();
}
The resolve method has to be implemented and the parameters should be given the same. Then the Observable should be the return type.
Step 2:
Then you have to make changes in your Router.module.ts
{ path: ‘Checkout’, component: CheckoutComponent, resolve: {userData: PreloadResolver}},
Step 3:
Then in the module which you have declared your component,Under the providers section add your resolver
providers:[ PreloadResolver]
Step 4:
In your Component, under your construction add the following code in your constructor
private route: ActivatedRoute
Add the following code to your constructor
route.data.do(console.log).subscribe(
data => { this.userData= data.userData; });
Now the data will be load on your load..,Happy Routing…!!!