Angular 10/9 Router: Resolve & Route Resolvers Example

  • Author: Techiediaries Team

The Angular 10 Router provides a resolve property that takes a route resolver and allows your application to fetch data before navigating to the route (i.e resolving route data).

How to Create an Angular 10 Route Resolver

You can create a route resolver in Angular 10 and previous versions by implementing the Resolve interface. For example,this a route resolver:

import { Injectable } from '@angular/core';
import { APIService } from './api.service';

import { Resolve } from '@angular/router';

@Injectable()
export class APIResolver implements Resolve<any> {
  constructor(private apiService: APIService) {}

  resolve() {
    return this.apiService.getItems();
  }
}

In the example, we assume we have already created an APIService which has a getItems() method that fetches data from a remote API endpoint.

We import the Resolve interface from the @angular/router package.

We then create an APIResolver class that implements the Resolve<any> interface.

In the constructor of the resolver we inject our APIService as apiService and we call the getItems() method of the service in the resolve() method that should be defined in any resolver

Accessing the Route Parameters in the Resolver

Often than not when resolving route data, you want to get access to the parameters of the route in the resolver. You can do that using the ActivatedRouteSnapshot class. For example, let's suppose our route has a date parameter that needs to be passed to the getItems(date) method:

import { Injectable } from '@angular/core';
import { APIService } from './api.service';

import { Resolve } from '@angular/router';

import { ActivatedRouteSnapshot } from '@angular/router';

@Injectable()
export class APIResolver implements Resolve<any> {
  constructor(private apiService: APIService) {}

  resolve(route: ActivatedRouteSnapshot) {
    return this.apiService.getItems(route.params.date);
  }
}

We import the ActivatedRouteSnapshot class from the @angular/router package and we provide a paramater route of type ActivatedRouteSnapshot to the resolve() method. Finally we use route.params.date to get the value of the date parameter.

Passing the Route Resolver to the Angular 10 Router

One final thing you need to do is to pass the resolver we created to resolve property of the corresponding route in the Routes array of your Angular routing module:

{
  path: 'items/:date',
  component: ItemsComponent,
  resolve: { items: APIResolver }
}

Conclusion

In this tutorial, we've seen how to resolve data using the resolve property and the route resolver (Resolve) of the Angular 10 router.


Sponsored Links