Resolver in Angular – Explained Angular Resolver With Examples Posted on 11 April 2023 by Ankur Akvaliya In regular Angular application development, the developers typically fetches data from the API with the ngOnInit hook, and then rendering it to the UI. While the Angular router waits for the API response 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 resolver in angular post, 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 and user interaction actions by simply loading Resolved 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 call that has to be included in the root module. A angular resolver development works like just a simple middleware, which can be executed before a component defined 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 make a click on the link. The Angular framework simply loads data from the respective component Angular executes certain code and returns a value or resolved data observable. You can collect the returned value or observable in the constructor or in ngOnInit, in the data provider class of your component which is about to load. Use the collected data for your purpose. Now you can load your component. In angular functional 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 deals with the execution process between clicking the link and loading the component. Develop a Single-Page Application With Angular Development We have a team of Angular developers having expertise in building feature-rich applications for all your business needs. Contact Us Why Should You Opt For Angular Resolvers? Angular Resolvers is responsible to fetch data or remove resolved data directly from the server before the activatedRoute of an upcoming component is finally 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 needed 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 in our Angular project. Let’s say the Angular 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 angular functional Resolver. How to Implement 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 implement a Routing Resolver in Angular web development project, the angular web developers need to create a new class that will be responsible for implementing the above-defined user interface. This Angular routing module interface defines two main route parameters (if you need them) with an interface resolve method: Route: It is of type ActivatedRouteSnapshot State: It is of type RouterStateSnapshot Here, you can create an API call that will get the data you need before your component initialization is loaded. The route parameter helps the developers to get private route parameters that may be used in the API response call for only resolved data just before corresponding component initialization takes place. On the other hand, the resolve method can return an Observable, a promise or just a custom type. Implementation of a Route Resolver in Angular To make it simple for you, you can even use a JSON placeholder to implement a demo API for fetching employee data to demonstrate or create API calls with Angular 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() data 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 service 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 data function of the Resolve method interface of the private 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 Angular’s router supports the fetched data. In case of an error, while fetching the data, you can send an empty observable and the router event data will not proceed to the route. The successful route navigation will be terminated at this point. To understand more details you can activate tracing support by passing a flag when it’s added to the app routes in your business data, like so: Copy @NgModule({ imports: [RouterModule.forRoot(routes, { enableTracing: true })], exports: [ RouterModule ] }) export class AppRoutingModule {} Our own Route reuse strategy help to avoid destroying the particular component during the navigation process.This last step is to create a component that will be called when the user goes to the /employees route. Typically, without an Angular Router Resolver, you will need to fetch 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. So, once the data load fails, you can efficiently replace it the same with an error message and a retry link. After you have created the employee’s component, you need to define the routes and tell the Angular router to use a resolver in Angular development ( EmployeeResolver). This Angular routing process could be achieved with the following angular resolver example code into the routing module file named 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 following route configuration named “const routes” and declare the EmployeeResolver as the component defined in the above code. The resolved data from the export class AppModule 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 fetching data into the employees’ component by using the activated route data property via the ActivatedRoute with the following code. After that, you are almost done. There is only one thing you need to do. You must get the fetching data into the employees’ component by using the activated route data property via the ActivatedRoute with the following code. 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 angular 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 load data depends on the activation process, and it will be there before the component rendered is loaded. Copy <h2>Fetched Employees:</h2> <ul> <li *ngFor="let employee of employees">{{ employee.name }}</li> </ul> Conclusion angular functional resolver can be beneficial because it ensures that data is available before a component is rendered. This can prevent issues with undefined or null data being used in a component’s template, which can cause errors and lead to poor user experience. So, we have seen the implementation of a angular resolver development that gets loaded data from the Employees API before navigating to a route related property 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.