Resolvers in Angular

Vignesh Ravichandran

--

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…!!!

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Vignesh Ravichandran
Vignesh Ravichandran

Written by Vignesh Ravichandran

Software Development Engineer with skills in Problem solving, Java Programming, Angular, Spring boot, Docker, Podman. www.youtube.com/@vigneshravichandran3096

No responses yet

Write a response