Usage of Resolvers in Angular 2.

Posted By :Ishaan Madan |30th June 2018

Introduction:

A common way to get and display the data from some API is routing a specific user to an angular component, and therafter calling a method present in service from the component’s  'ngOnInit' hook to fetch the necessary information. In this approach we often display some loading indicator till the response is arrived from the server.
However, there is another way called 'route resolver' which allows us to get the necessary data prior to navigation to a particular route. 

Tip- Resolvers should not be overused

We should load only the relevant data through resolvers to display the important sections of the page and rest of the data should be fetched asynchronously.

 

Resolver usage example in route config :

// main.ts

import { TransactionResolver } from './resolvers/transaction.resolver.ts';

export const routes: RouterConfig = [
  {
    path: 'transactions/:id',
    component: TransactionComponent,
    resolve: {
      transaction: TransactionResolver
    }
  }
];

bootstrap(AppComponent, [
  provideRouter(routes)
])
 
In the above example, we pass a 'TransactionResolver' class in the 'resolve' property of the route config object. Using this property Angular will run all the classes given inside the object, before loading the 'TransactionComponentcomponent given in the route.
 
Resolver Class Implementation
 
// transaction.resolver.ts

import { Injectable } from '@angular/core';
import { Resolve, ActivatedRouteSnapshot } from '@angular/router';
import { Observable } from 'rxjs/Rx';
import { TransactionService } from '../services/transaction.service';

@Injectable()
export class TransactionResolver implements Resolve {
  constructor(
    private transactionService: TransactionService
  ) {}

  resolve(route: ActivatedRouteSnapshot): Observable {
    return this.transactionService.getById(route.params.id);
  }
}
  • The exported class should be Injectable
  • The class should implements 'Resolve<any>' interface with one method 'resolve(): Observable<any>'
Thanks

About Author

Ishaan Madan

Ishaan is an experienced Wordpress/PHP Lead Developer, he has good knowledge of HTML, CSS, PHP, Wordpress, Jquery and AJAX. His hobbies are playing basketball and reading about defence.

Request For Proposal

Sending message..

Ready to innovate ? Let's get in touch


Notice: Undefined index: HTTP_REFERER in /var/html/www/AI/wp-content/themes/oxides-child/functions.php on line 272

Notice: Undefined index: HTTP_REFERER in /var/html/www/AI/wp-content/themes/oxides-child/functions.php on line 272

Notice: Undefined index: HTTP_REFERER in /var/html/www/AI/wp-content/themes/oxides-child/functions.php on line 272

Notice: Undefined index: HTTP_REFERER in /var/html/www/AI/wp-content/themes/oxides-child/functions.php on line 272

Chat With Us