Resolver in Angular -Basic Understanding With Example

 

Published On:

  August, 22, 2022
Read Time 9.63 Minute Read
Copy
var promise = new Promise((resolve, reject) => {
    resolve(“Promise Resolved”);
})
promise.then((success) => {
    console.log(success);
})
.catch(function(error) => {
    console.log(error);
});
// Output: Promise Resolved
Resolver in Angular -Basic Understanding With Example

In the regular Angular application development, the developers typically fetches data from the API with the ngOnInit hook, and then rendering it to the UI. While waiting for the api to return the complete data, the component renders the loading, skeleton. etc

But, there’s also alternate way to get the data first and then redirect your component. It’s call Route Resolver. One of the common issues that many Angular developers have in mind is how to handle multiple requests without affecting the user experience.

One of the global solutions to this issue is to implement Angular Resolver. In this article, we have come up with an answer to the above question and will understand the implementation of Route Resolver in Angular.

What is Resolver in Angular?

Angular route resolver allows the developers to get data before navigating to the new route. In simple words, we can say that it’s a smooth approach that quickly improves user experience by simply loading data just before the user navigates to any specific component.

A Resolver in Angular development is nothing but a class that implements the Resolve interface of Angular Router. We can say that Resolver is simply a service that has to be included in the root module. A Resolver works like middleware, which can be executed before a component is loaded.

To know more about Angular in detail, you can read the article on what is Angular.

Difference Between Basic Routing Flow and Angular Resolver Flow

Basic Routing Flow Angular Resolver Flow
The end-user clicks on link The end-user clicks the link.
The Angular framework simply loads the respective component Angular executes certain code and returns a value or observable.
You can collect the returned value or observable in the constructor or in ngOnInit, in the class of your component which is about to load.
Use the collected data for your purpose.
Now you can load your component.

In Angular resolver, steps 2,3 and 4 are done with a code called Resolver.

As a concluding point, we can say that Resolver in Angular development is an intermediate code that is executed between clicking the link and loading the component.

Planning To Develop a Robust Single-Page Application?

Albiorix is a leading AngularJS Development Company having core expertise in designing and building feature-rich applications for all your business needs.

Why Should You Opt For Angular Resolvers?

Angular Resolvers is responsible for fetch remove data directly from the server before the activatedRoute of an upcoming component is activated. There is no involvement of a spinner until the data is fetched because the dedicated angular developer find it challenging to navigate to the next component unless the server data is retrieved.

To understand it better, let’s take one scenario- we want to display the array of items in a component received in an unordered list or table.

Let’s say the developer is giving the command *ngIf=” passing some condition” and our business logic depends upon the length of an array, which will be altered once the API call is successful.

We might face an issue in such a case as the component will be ready before receiving the data (the array item isn’t yet with us).

Here comes Route Resolver to rescue. We can use Angular’s Route Resolver class for fetching the data before your component is loaded. And then, the conditional statements can work smoothly with the Resolver.

An Example of Angular Resolver

First of all, we need to understand the working process of the Resolve Interface. It is an essential part that Angular developers need to follow.

Copy
export interface Resolve {
  resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable | Promise | T {
  return 'Data resolved here...'
  }
} }
}

To create a Route Resolver in Angular application, the developers need to create a new class that will be responsible for implementing the above defined interface. In this interface, you’ll come across two main parameters (if you need them) with a resolve function:

  • Route: It is of type ActivatedRouteSnapshot
  • State: It is of type RouterStateSnapshot

Here, you can make an API call that will get the data you need before your component is loaded.

The route parameter helps the developers to get route parameters that may be used in the API call. On the other hand, the resolve method can return an Observable, a promise or just a custom type.

Implementation of a Route Resolver

To make it simple for you, you can even use a JSON placeholder to create a demo API for fetching employee data to demonstrate API calls with route resolvers.

First of all, we will need a service that will fetch the employee data for us. In this service, we have a function called getEmployees() that returns an observable.

Copy
@Injectable({
providedIn: 'root'
})
export class EmployeeApiService {
  constructor(private http: HttpClient) { }
  private employeesEndpoint = "https://jsonplaceholder.typicode.com/employees";
  getEmployees(): Observable {
      return this.http.get(this.employeesEndpoint);
  }
}

It is important no to subscribe to the function getEmployees(). The route resolver called EmployeeResolver will take care of this for you. The next step is to create a new service called EmployeeResolver which will implement the resolve function of the Resolve interface of the router.

Copy
@Injectable({
providedIn: 'root'
})
export class EmployeeResolverService implements Resolve {
  constructor(private employeeApi: EmployeeApiService) { }
  resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    return this.employeeApi.getEmployees().pipe(
      catchError((error) => {
      return empty();
      });
    );
  }
}

This service, EmployeeResolver, will subscribe automatically to the getEmployees observable and provide the router with the fetched data. In case of an error, while fetching the data, you can send an empty observable and the router will not proceed to the route.

The navigation will be terminated at this point. This last step is to create a component that will be called when the user goes to the /employees route. Typically, without a Resolver, you will need to fetch the data on the ngOnInit hook of the component and handle the errors caused by ‘no data’ exists. The employee’s component is a simple one. It just gets the employee’s data from the ActivatedRoute and displays them into an unordered list.

After you have created the employee’s component, you need need to define the routes and tell the router to use a resolver ( EmployeeResolver). This could be achieved with the following code into the app-routing.modulte.ts.

Copy
const routes: Routes = [
{ path: 'employees', component: EmployeesComponent, resolve: { employees: EmployeeResolverService } }
];

@NgModule({
  imports: [
  CommonModule,
  FormsModule,
  HttpClientModule,
  RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

You need to set the resolve property into the employee’s route and declare the EmployeeResolver. The data will be passed into an object with a property called employees. After that, you are almost done. There is only one thing you need to do. You must get the fetched data into the employees’ component via the ActivatedRoute with the following code.

Copy
constructor(private activatedRoute: ActivatedRoute) { }

employees: any[];

ngOnInit() {
  this.activatedRoute.data.subscribe((data: { employees: any }) => {
  this.employees = data.employees;
  });
}

Then, you can just display them into HTML without any *ngIf statements ( *ngIf=”employees && employees.length > 0 ) because the data will be there before the component is loaded.

Copy

Fetched Employees:

  • {{ employee.name }}

Conclusion

So, we have seen the implementation of a route resolver that gets data from the Employees API before navigating to a route that displayed the gathered data. And it is made possible by utilizing @angular/router, @angular/common/http, and rxjs. Get in touch with one of the best AngularJS Development company that always strive to provide the best possible web app solutions for your business requirements.

Ankur Akvaliya is Sr. Software Engineer at Albiorix Technology. He is a dedicated and hard-working person to deals with any technological needs. He is prominent in working with object-oriented design, problem resolution, requirement gathering, and finally debugging the code.

Ankur Akvaliya

Ankur Akvaliya is Sr. Software Engineer at Albiorix Technology. He is a dedicated and hard-working person to deals with any technological needs. He is prominent in working with object-oriented design, problem resolution, requirement gathering, and finally debugging the code.

Key Clients

Get in Touch


    Our Offices
    Head Office & Development Center
    Albiorix Head Office India India

    A-804, Safal Profitaire, Prahladnagar,
    Ahmedabad, Gujarat 380015.

    Sales Office
    Albiorix Development Center Australia Australia

    81-83 Campbell Street,
    Surry Hills, NSW 2010, Australia